language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def upload_complete(self, path, url, quiet): """ function to complete an upload to retrieve a path from a url Parameters ========== path: the path for the upload that is read in url: the url to send the POST to quiet: suppress verbose output (default ...
python
def redis_es_sub(session, tables, redis_dsn, strict=False, namespace=None, ttl=3600*24*3, socket_timeout=1): """Redis EventSourcing sub. This sub should be used together with sqlalchemy_es_pub, it will use RedisEventStore as events storage layer and use the prepare-commit pattern in :f...
python
def render_table(self, headers, rows, style=None): """ Format input to textual table. """ table = self.table(headers, rows, style) table.render(self._io)
python
def validateClassifier(self, cut_detect, cut_train, cut_geometry, y_pred): """ Make some diagnostic plots """ color = {'detect': 'Red', 'nondetect': 'Gold', 'why_not': 'none', 'actual': 'DodgerBlue', 'hsc': 'lime'} ...
python
def gpu_mem_get(id=None): "get total, used and free memory (in MBs) for gpu `id`. if `id` is not passed, currently selected torch device is used" if not use_gpu: return GPUMemory(0, 0, 0) if id is None: id = torch.cuda.current_device() try: handle = pynvml.nvmlDeviceGetHandleByIndex(id) ...
python
def load_ipython_extension(ip): """Load the extension in IPython.""" ip.register_magics(FortranMagics) # enable fortran highlight patch = ("IPython.config.cell_magic_highlight['magic_fortran'] = " "{'reg':[/^%%fortran/]};") js = display.Javascript(data=patch, ...
python
def handle_inform(self, msg): """Dispatch an inform message to the appropriate method. Parameters ---------- msg : Message object The inform message to dispatch. """ method = self._inform_handlers.get( msg.name, self.__class__.unhandled_inform) ...
java
protected void loadAgent(Object pVm, OptionsAndArgs pOpts,String ... pAdditionalOpts) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Class clazz = pVm.getClass(); Method method = clazz.getMethod("loadAgent",String.class, String.class); String args = pOpts.toAge...
java
static public Number getElementAt(Matrix matrix, int row, int column){ List<Array> arrays = matrix.getArrays(); List<MatCell> matCells = matrix.getMatCells(); Matrix.Kind kind = matrix.getKind(); switch(kind){ case DIAGONAL: { // "The content is just one Array of numbers representing the diagonal ...
python
def dump(node): """ A very verbose representation of the node passed. This is useful for debugging purposes. """ def _format(node): if isinstance(node, AST): return '%s(%s)' % (node.__class__.__name__, ', '.join('%s=%s' % (a, _format(b)) ...
python
def Iax(mt, x, *args): """ (Ia)x : Returns the present value of annuity-certain at the end of the first year and increasing linerly. Arithmetically increasing annuity-late """ return Sx(mt, x + 1) / Dx(mt, x)
python
def tree_build(self): """Build a tree from the taxonomy data present in this `ClassificationsDataFrame` or `SampleCollection`. Returns ------- `skbio.tree.TreeNode`, the root node of a tree that contains all the taxa in the current analysis and their parents leading back...
python
def _preprocess_Y(self, Y, k): """Convert Y to prob labels if necessary""" Y = Y.clone() # If preds, convert to probs if Y.dim() == 1 or Y.shape[1] == 1: Y = pred_to_prob(Y.long(), k=k) return Y
python
def get_chunk_size(N, n): """Given a dimension of size 'N', determine the number of rows or columns that can fit into memory. Parameters ---------- N : int The size of one of the dimension of a two-dimensional array. n : int The number of times an 'N' by 'chunks_size' arr...
java
public byte[] getValueAsArray() { ByteBuffer buffer = getValue(); byte[] result = new byte[buffer.remaining()]; buffer.get(result); return result; }
java
public static Observable<String> getFileExtension(final String fileName) { return Observable.fromCallable(new Func0<String>() { @Override public String call() { return fileName.substring((fileName.lastIndexOf('.')) + 1); } }); }
java
@JsonCreator public static GeoDistance create(String json) { try { for (GeoDistanceUnit geoDistanceUnit : GeoDistanceUnit.values()) { for (String name : geoDistanceUnit.getNames()) { if (json.endsWith(name)) { double value = Double.pars...
java
StatusStream getRetweetStream() throws TwitterException { ensureAuthorizationEnabled(); try { return new StatusStreamImpl(getDispatcher(), http.post(conf.getStreamBaseURL() + "statuses/retweet.json" , new HttpParameter[]{stallWarningsParam}, auth, null), conf); } ...
python
def _check_last_arg_pattern(self, current_arg_pattern, last_arg_pattern): """Given a "current" arg pattern (that was used to match the last actual argument of an expression), and another ("last") argument pattern, raise a ValueError, unless the "last" argument pattern is a "zero or more"...
java
@Override public void setY(double min, double max) { if (min <= max) { this.miny = min; this.maxy = max; } else { this.miny = max; this.maxy = min; } }
java
public static void printTimeDifference(final long pStartTime, final long pEndTime, final PrintStream pPrintStream) { if (pPrintStream == null) { System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE); return; } pPrintStream.println(buildTimeDifference(pStartTime, pEndTime)); }
python
def delete_table(self, table, retry=DEFAULT_RETRY, not_found_ok=False): """Delete a table See https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/delete Args: table (Union[ \ :class:`~google.cloud.bigquery.table.Table`, \ :class:`...
python
def parse_type_system_definition(parser): # type: (Parser) -> Any """ TypeSystemDefinition : - SchemaDefinition - TypeDefinition - TypeExtensionDefinition - DirectiveDefinition TypeDefinition : - ScalarTypeDefinition - ObjectTypeDefinition - Interfa...
python
def do_renegotiate(self) -> None: """Initiate an SSL renegotiation. """ if not self._is_handshake_completed: raise IOError('SSL Handshake was not completed; cannot renegotiate.') self._ssl.renegotiate() self.do_handshake()
python
def create_feed(self, feed): """CreateFeed. [Preview API] Create a feed, a container for various package types. :param :class:`<Feed> <azure.devops.v5_0.feed.models.Feed>` feed: A JSON object containing both required and optional attributes for the feed. Name is the only required value. ...
python
def esinw(b, orbit, solve_for=None, **kwargs): """ Create a constraint for esinw in an orbit. If 'esinw' does not exist in the orbit, it will be created :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter str orbit: the label of the orbit in which this constraint should be ...
python
def ensure_dir (path, parents=False): """Returns a boolean indicating whether the directory already existed. Will attempt to create parent directories if *parents* is True. """ if parents: from os.path import dirname parent = dirname (path) if len (parent) and parent != path: ...
java
final LocalTransactionCoordinator suspendLocalTx() // 131880-6 { // d173641 Begins LocalTransactionCoordinator lCoord = null; // d165585 if (TraceComponent.isAnyTracingEnabled() && // d527372 (tc.isEventEnabled() || TETxLifeCycleInfo.isTraceEnabled())) { ...
python
def write(self, file): """Write the image to the open file object. See `.save()` if you have a filename. In general, you can only call this method once; after it has been called the first time the PNG image is written, the source data will have been streamed, and cannot...
python
def set_led(self, led_id, color): """ Set color of an led :param led_id: id of led to set color :type led_id: int :param color: list of rgb values of new colors. eg. [255, 255, 255] :type color: list :returns: true if successful :rtype: bool """ ...
python
def add_comment(self, line): """Add a Comment object to the section Used during initial parsing mainly Args: line (str): one line in the comment """ if not isinstance(self.last_item, Comment): comment = Comment(self._structure) self._structur...
java
public void marshall(GeoMatchConstraint geoMatchConstraint, ProtocolMarshaller protocolMarshaller) { if (geoMatchConstraint == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(geoMatchConstraint.getTyp...
java
protected int readWord(byte[] data, int offset) { int low = data[offset] & 0xff; int high = data[offset + 1] & 0xff; return high << 8 | low; }
python
def show(self): """ Pretty-print instance data """ if not self.data: return if self.data.get('continue'): return ptitle = self.params.get('title') dtitle = self.data.get('title') pageid = self.params.get('pageid') seed = ...
python
def is_log_format(value): u""" Check whether the value as argument be included the following list. ['ltsv', 'combined'] """ log_levels = ['ltsv', 'combined'] if value in log_levels: return value else: err_message = ('"log_format" supported following value: ' ...
python
def _perform_reset(self, reset_type): """! @brief Perform a reset of the specified type.""" if reset_type is Target.ResetType.HW: self.session.probe.reset() elif reset_type is Target.ResetType.SW_EMULATED: self._perform_emulated_reset() else: if reset_...
python
def get_bootstrap_from_recipes(cls, recipes, ctx): '''Returns a bootstrap whose recipe requirements do not conflict with the given recipes.''' info('Trying to find a bootstrap that matches the given recipes.') bootstraps = [cls.get_bootstrap(name, ctx) for name in c...
java
public Object invokeSetter(final Object instance, final Object value) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { final Class<?> valueClass = value.getClass(); final Method method = getInvokableMethodForClass(valueClass); if (method == null) {...
python
def getURL(self, CorpNum, UserID, ToGo): """ 문자 관련 팝빌 URL args CorpNum : 팝빌회원 사업자번호 UserID : 팝빌회원 아이디 TOGO : BOX (전송내역조회 팝업) return 팝빌 URL raise PopbillException """ if ...
java
@Nonnull private DAType findFixedResolution(Element element) { Name qualifiedName = element.accept(QualifiedNameExtractor.QUALIFIED_NAME_EXTRACTOR, null); // qualified reference to Type in code if (qualifiedName != null && !qualifiedName.contentEquals(element.getSimpleName())) { return ensureNonnull...
java
@Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { Object entity = context.getEntity(); if (entity instanceof Images.Captcha || entity instanceof Captcha) { context.setMediaType(IMG_TYPE); context.getHeaders().p...
java
private static String[] splitByCharacterType(String str, boolean camelCase) { if (str == null) { return null; } if (str.length() == 0) { return new String[0]; } char[] c = str.toCharArray(); ArrayList<String> list = new ArrayList<String>(); ...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "parameterName", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "name") public JAXBElement<CodeType> createParameterName(CodeType value) { return new JAXBElement<CodeType>(_ParameterName_QNAME, CodeType.class,...
python
def _create_handler(self, handler_class, level): """Create an handler for at specific level.""" if handler_class == logging.StreamHandler: handler = handler_class() handler.setLevel(level) elif handler_class == logging.handlers.SysLogHandler: handler = handler...
python
def read(self, *args): """Handles raw client requests and distributes them to the appropriate components""" self.log("Beginning new transaction: ", args, lvl=network) try: sock, msg = args[0], args[1] user = password = client = clientuuid = useruuid = requestdata...
java
@Test public void MPJwtBadMPConfigAsEnvVars_GoodMpJwtConfigSpecifiedInServerXml() throws Exception { resourceServer.reconfigureServerUsingExpandedConfiguration(_testName, "rs_server_AltConfigNotInApp_goodServerXmlConfig.xml"); standardTestFlow(resourceServer, MpJwtFatConstants.NO_MP_CONFIG_IN_APP_R...
java
public static Byte decodeByteObjDesc(byte[] src, int srcOffset) throws CorruptEncodingException { try { int b = src[srcOffset]; if (b == NULL_BYTE_HIGH || b == NULL_BYTE_LOW) { return null; } return decodeByteDesc(src, srcOffset...
python
def create(file_path): """Create a default .sciunit config file if one does not already exist.""" if os.path.exists(file_path): raise IOError("There is already a configuration file at %s" % file_path) with open(file_path, 'w') as f: config = configparser.ConfigParser() ...
java
private void start(final WebDriver webDriver, final boolean isResuming) { try { Validate.validState(isStopped, "The crawler is already running."); this.webDriver = Validate.notNull(webDriver, "The webdriver cannot be null."); // If the crawl delay strategy is set to ada...
java
public final MonitoredResourceDescriptor getMonitoredResourceDescriptor( MonitoredResourceDescriptorName name) { GetMonitoredResourceDescriptorRequest request = GetMonitoredResourceDescriptorRequest.newBuilder() .setName(name == null ? null : name.toString()) .build(); ret...
java
@Override public ReactiveSeq<T> stream() { return ReactiveSeq.generate(() -> get()) .limit(1) .filter(t -> t.isSuccess()) .map(t->t.orElse(null)); }
python
def destroy_vm_by_uuid(self, si, vm_uuid, vm_path, logger): """ destroy the given vm :param si: pyvmomi 'ServiceInstance' :param vm_uuid: str uuid of the vm to destroyed :param vm_path: str path to the vm that will be destroyed :param logger: """ if v...
java
public static boolean useDefaultWeekmodel(Locale locale) { String fw = locale.getUnicodeLocaleType("fw"); if ((fw != null) && (getWeekdayISO(fw) != 0)) { return false; } return getRegion(locale).isEmpty(); }
java
public void marshall(AddressConfiguration addressConfiguration, ProtocolMarshaller protocolMarshaller) { if (addressConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(addressConfiguratio...
python
def do_dock6_flexible(self, ligand_path, force_rerun=False): """Dock a ligand to the protein. Args: ligand_path (str): Path to ligand (mol2 format) to dock to protein force_rerun (bool): If method should be rerun even if output file exists """ log.debug('{}: run...
java
public void marshall(UnprocessedNamedQueryId unprocessedNamedQueryId, ProtocolMarshaller protocolMarshaller) { if (unprocessedNamedQueryId == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(unprocesse...
python
def start(project, logfile, time_format): "start tracking for <project>" records = read(logfile, time_format) if records and not records[-1][1][1]: print "error: there is a project already active" return write(server.start(project, records), logfile, time_format) print "starting work on %s" % color...
java
private static Set<Label> getAttributeImplicitRelationTypeLabes(Set<Type> types) { // If the sub graph contains attributes, we may need to add implicit relations to the path return types.stream() .filter(Concept::isAttributeType) .map(attributeType -> Schema.ImplicitType....
java
@Override public synchronized AttachmentResourceWritable addAttachment(File file, AttachmentType type, String name) throws RepositoryException { AttachmentResourceImpl at = new AttachmentResourceImpl(file, name); at.setType(type); // Massive can set this, but we need to know it before then, ...
java
public void lock(String statement, Object parameter) { // do not perform locking if H2 database is used. H2 uses table level locks // by default which may cause deadlocks if the deploy command needs to get a new // Id using the DbIdGenerator while performing a deployment. if (!DbSqlSessionFactory.H2.equ...
java
public NetworkProfileInner getByResourceGroup(String resourceGroupName, String networkProfileName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, networkProfileName).toBlocking().single().body(); }
python
def _utc_year(self): """Return a fractional UTC year, for convenience when plotting. An experiment, probably superseded by the ``J`` attribute below. """ d = self._utc_float() - 1721059.5 #d += offset C = 365 * 100 + 24 d -= 365 d += d // C - d // (4 * C...
python
def argsort(self, *args, **kwargs): """ Returns the indices that would sort the index and its underlying data. Returns ------- argsorted : numpy array See Also -------- numpy.ndarray.argsort """ nv.validate_argsort(args, kwargs) ...
python
def bulk_shear(pressure, u, v, heights=None, bottom=None, depth=None): r"""Calculate bulk shear through a layer. Layer top and bottom specified in meters or pressure. Parameters ---------- pressure : `pint.Quantity` Atmospheric pressure profile u : `pint.Quantity` U-component o...
python
def _convert_2_0_0_alpha(topo, topo_path): """ Convert topologies from GNS3 2.0.0 alpha to 2.0.0 final. Changes: * No more serial console * No more option for VMware / VirtualBox remote console (always use telnet) """ topo["revision"] = 6 for node in topo.get("topology", {}).get("node...
java
public static String encrypt(CharSequence data, CharSequence cipherKey) { final int dataLen = data.length(); final int cipherKeyLen = cipherKey.length(); final char[] cipherArray = new char[dataLen]; for (int i = 0; i < dataLen / cipherKeyLen + 1; i++) { for (int t = 0; t < cipherKeyLen; t++) { i...
java
public Map<String,InputStream> loadLinkedWorkbooks(String[] fileNames) throws IOException { HashMap<String,InputStream> result = new HashMap<>(); if (fileNames==null) { return result; } for (String currentFile: fileNames) { Path currentPath=new Path(currentFile); InputStream currentInputStream = openFile(curr...
python
def _get_value_type(kind): """Returns a _APEValue subclass or raises ValueError""" if kind == TEXT: return APETextValue elif kind == BINARY: return APEBinaryValue elif kind == EXTERNAL: return APEExtValue raise ValueError("unknown kind %r" % kind)
java
@Override protected void onChunkSize(RTMPConnection conn, Channel channel, Header source, ChunkSize chunkSize) { log.debug("onChunkSize"); // set read and write chunk sizes RTMP state = conn.getState(); state.setReadChunkSize(chunkSize.getSize()); state.setWriteChunkSiz...
java
@Override public List<GroupState> decodeContent(InputStream in, Charset charset) throws IOException { // 解析报文内容 byte[] bytes = new byte[(int) getContentLength()]; int contentSize = in.read(bytes); // 此处fastdfs的服务端有bug if (contentSize != getContentLength()) { try {...
java
public static JSONArray fetchDirectoryObjectJSONArray(JSONObject jsonObject) throws Exception { JSONArray jsonArray = new JSONArray(); jsonArray = jsonObject.optJSONObject("responseMsg").optJSONArray("value"); return jsonArray; }
python
def _load_vocab_file(vocab_file, reserved_tokens=None): """Load vocabulary while ensuring reserved tokens are at the top.""" if reserved_tokens is None: reserved_tokens = RESERVED_TOKENS subtoken_list = [] with tf.gfile.Open(vocab_file, mode="r") as f: for line in f: subtoken = _native_to_unicode...
java
public static void log(Logger logger, Level level, String message, Throwable throwable, Object parameter) { if (logger.isLoggable(level)) { final String formattedMessage = ...
java
private CmsXmlContent getContentDocument(CmsFile file, boolean fromCache) throws CmsXmlException { CmsXmlContent content = null; if (fromCache) { content = getSessionCache().getCacheXmlContent(file.getStructureId()); } if (content == null) { content = CmsXmlConte...
python
def focusInEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(ControlWidget, self).focusInEvent(event)
java
public Node removeChild(final String name) { final Node node = getSingle(name); if (node != null) { removeChild(node); } return node; }
java
public ColumnMapper getMapper(String field) { String[] components = field.split("\\."); for (int i = components.length - 1; i >= 0; i--) { StringBuilder sb = new StringBuilder(); for (int j = 0; j <= i; j++) { sb.append(components[j]); if (j < i) s...
java
public int size() { int acc = 0; for (Map.Entry<String, List<Cell>> entry : cells.entrySet()) { acc += entry.getValue().size(); } return acc; }
python
def itable(*args, **kwargs): ''' itable(...) yields a new immutable table object from the given set of arguments. The arguments may be any number of maps or itables followed by any number of keyword arguments. All the entries from the arguments and keywords are collapsed left-to-right (respecting la...
python
def _notifyDone(self): ''' Allow any other editatoms waiting on me to complete to resume ''' if self.notified: return self.doneevent.set() for buid in self.mybldgbuids: del self.allbldgbuids[buid] self.notified = True
python
def delete_dataset(self, dataset, delete_nonempty=True): """Deletes a dataset (and optionally any tables in it), if it exists. :param dataset: :type dataset: BQDataset :param delete_nonempty: if true, will delete any tables before deleting the dataset """ if no...
python
def apply_to_compound(self, guest, guest_port_name='down', host=None, backfill=None, backfill_port_name='up', scale=True): """Attach copies of a guest Compound to Ports on a host Compound. Parameters ---------- guest : mb.Compound The Compound proto...
java
protected String processFileName(String name) { int pos = name.lastIndexOf("/"); if (pos >= 0) { name = name.substring(pos + 1); } pos = name.lastIndexOf("\\"); if (pos >= 0) { name = name.substring(pos + 1); } return name; }
java
public DatabaseException convertError(Exception ex) { DatabaseException eDB = null; int iError = DBConstants.ERROR_RETURN; String strMessage = "Error!"; if (ex != null) strMessage = ex.getMessage(); if (ex instanceof SQLException) { SQLExceptio...
java
@SuppressWarnings("unchecked") public <T> T getArgument(String name) { return (T) arguments.get(name); }
java
@Override public Set<URI> listOutputs(URI operationUri) { if (operationUri == null) { return ImmutableSet.of(); } return ImmutableSet.copyOf(this.opOutputMap.get(operationUri)); }
python
def main(database_dir, target_dir): """Generate CSV files from a CronosPro/CronosPlus database.""" if not os.path.isdir(database_dir): raise click.ClickException("Database directory does not exist!") try: os.makedirs(target_dir) except: pass try: parse(database_dir, t...
java
private IBlockRenderer getBlockRendererOverride(IBlockAccess world, BlockPos pos, IBlockState state) { for (BlockRendererOverride overrides : blockRendererOverrides) { IBlockRenderer renderer = overrides.get(world, pos, state); if (renderer != null) return renderer; } return null; }
java
@SuppressWarnings("unchecked") public static void run(final Properties properties) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { System.out.println("Parsing started: recommendation file"); Fi...
java
private void putSuperAndThisConstructorSymbols() { IGosuClassInternal thisClass = getGosuClass(); IGosuClassInternal superClass = thisClass.getSuperClass(); if( superClass != null ) { for( DynamicFunctionSymbol dfs : superClass.getConstructorFunctions() ) { if( superClass.isAccessi...
python
def get(cls, issue_type): """Returns the IssueType object for `issue_type`. If no existing object was found, a new type will be created in the database and returned Args: issue_type (str,int,IssueType): Issue type name, id or class Returns: :obj:`IssueType` ...
java
public static CellRangeAddress mergeCells(final Sheet sheet, int startCol, int startRow, int endCol, int endRow) { ArgUtils.notNull(sheet, "sheet"); // 結合先のセルの値を空に設定する for(int r=startRow; r <= endRow; r++) { for(int c=startCol; c <= endCol; c++) { if(r == sta...
python
def iterative_encoder_decoder(encoder_input, encoder_self_attention_bias, encoder_decoder_attention_bias, query, hparams): """Iterative encoder decoder.""" for _ in range(hparams.num_rec_steps): ...
python
def reload(self): """Reload the metadata for this instance. For example: .. literalinclude:: snippets.py :start-after: [START bigtable_reload_instance] :end-before: [END bigtable_reload_instance] """ instance_pb = self._client.instance_admin_client.get_i...
python
def list(self): """ List all backups as WorkspaceBackup objects, sorted descending by lastmod. """ backups = [] for d in glob(join(self.backup_directory, '*')): backups.append(WorkspaceBackup.from_path(d)) backups.sort(key=lambda b: b.lastmod, reverse=True) ...
java
public void value(String expectedValue, 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 _decompose(string, n): '''Given string and multiplier n, find m**2 decomposition. :param string: input string :type string: str :param n: multiplier :type n: int :returns: generator that produces m**2 * string if m**2 is a factor of n :rtype: generator of 0 or 1 ''' binary = [i...
java
public <T> PagedList<T> fetchPreviousPagedConnections(PagedList<T> page, Class<T> type) { if (null != page && null != page.getPreviousPage() && !"".equals(page.getPreviousPage().getFullUrl().trim())) { URIBuilder uriBuilder = URIBuilder.fromUri(page.getPreviousPage().getFullUrl()); JsonNode jsonNode = getRestTe...
java
private void marshalCreatedAndUpdatedTimestamp() { PropertyMetadata createdTimestampMetadata = entityMetadata.getCreatedTimestampMetadata(); PropertyMetadata updatedTimestampMetadata = entityMetadata.getUpdatedTimestampMetadata(); long millis = System.currentTimeMillis(); if (createdTimestampMetadata !=...
python
def K_branch_diverging_Crane(D_run, D_branch, Q_run, Q_branch, angle=90): r'''Returns the loss coefficient for the branch of a diverging tee or wye according to the Crane method [1]_. .. math:: K_{branch} = G\left[1 + H\left(\frac{Q_{branch}}{Q_{comb} \beta_{branch}^2}\right)^2 - J\left...