language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def defer( self, func: typing.Callable[[], typing.Any], until: typing.Union[int, float]=-1, ) -> typing.Any: """Defer the execution of a function until some clock value. Args: func (typing.Callable[[], typing.Any]): A callable that accepts no ...
java
public static ZonedDateTime toZonedDateTimeUtc(final long epoch) { final EpochUnits units = EpochUnits.valueOf(epoch); return toZonedDateTimeUtc(epoch, units); }
java
private static int popcount_fbsd2_2(int[] data, int x, int n) { int cnt = 0; for (x++; x < n; x += 2) cnt += Integer.bitCount(data[x]); return cnt; }
java
public static RawJsonDocument create(String id, int expiry, String content) { return new RawJsonDocument(id, expiry, content, 0, null); }
java
public static boolean cs_pvec(int [] p, DZcsa b, DZcsa x, int n) { int k ; if (x == null || b == null) return (false) ; /* check inputs */ for (k = 0 ; k < n ; k++) x.set(k, b.get(p != null ? p [k] : k)) ; return (true) ; }
java
private void combineHistogramDifferentBuckets(FixedBucketsHistogram otherHistogram) { if (otherHistogram.getLowerLimit() >= upperLimit) { outlierHandler.handleOutliersCombineDifferentBucketsAllUpper(otherHistogram); } else if (otherHistogram.getUpperLimit() <= lowerLimit) { outlierHandler.handleOu...
java
private static final void auditNamedValues(String m, Map<String, ?> namedValues) { if (logger.isDebugEnabled()) { assert namedValues != null; for (Iterator<String> outer = namedValues.keySet().iterator(); outer .hasNext();) { Object name = outer.next()...
java
public static <T> void isNotSame( final T argument, String argumentName, final T object, String objectName ) { if (argument == object) { if (objectName == null) objectName = getObjectNam...
java
public static Map<TypeVariable, Type> getTypeVariableMap(Class<?> clazz) { Map<TypeVariable, Type> typeVariableMap = typeVariableCache.get(clazz); if (typeVariableMap == null) { typeVariableMap = new HashMap<TypeVariable, Type>(); // interfaces extractTypeVariablesFromGenericInterfaces(clazz.getGenericIn...
python
def run_service_actions(self): """Run any actions on services requested.""" if not self.service_actions: return for svc_action in self.service_actions: name = svc_action['service'] actions = svc_action['actions'] log("Running service '%s' actions ...
java
public void setChild(final int index, final String label) { final Parse newChild = (Parse) this.parts.get(index).clone(); newChild.setLabel(label); this.parts.set(index, newChild); }
python
def process_rewards(self, rewards): """Clips, rounds, and changes to integer type. Args: rewards: numpy array of raw (float) rewards. Returns: processed_rewards: numpy array of np.int64 """ min_reward, max_reward = self.reward_range # Clips at min and max reward. rewards = np...
java
@Override public Partition[] getPartitions(S config) { jdbcDeepJobConfig = initConfig(config, jdbcDeepJobConfig); int upperBound = jdbcDeepJobConfig.getUpperBound(); int lowerBound = jdbcDeepJobConfig.getLowerBound(); int numPartitions = jdbcDeepJobConfig.getNumPartitions(); ...
python
def convert_to_record(func): """Wrap mongodb record to a dict record with default value None """ @functools.wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) if result is not None: if isinstance(result, dict): return _record(...
python
def invoke(self, function_name, raw_python=False, command=None, no_color=False): """ Invoke a remote function. """ # There are three likely scenarios for 'command' here: # command, which is a modular function path # raw_command, which is a string of python to execute...
java
public boolean interrupt (final String fireInstanceId) throws UnableToInterruptJobException { final ICommonsList <IJobExecutionContext> jobs = getCurrentlyExecutingJobs (); IJob job = null; for (final IJobExecutionContext jec : jobs) { if (jec.getFireInstanceId ().equals (fireInstanceId)) ...
java
private void waitForConditionOrTimeout() throws InterruptedException { waitStart = System.currentTimeMillis(); while (state == State.RequestSent || state == State.Initial) { long timeout = connection.getReplyTimeout(); long remainingWaitMillis = timeout - (System.currentTimeMilli...
python
def title(self): """ The title of this window """ with switch_window(self._browser, self.name): return self._browser.title
python
async def add_claims(self, payload, user, *args, **kwargs): """ Injects standard claims into the payload for: exp, iss, iat, nbf, aud. And, custom claims, if they exist """ delta = timedelta(seconds=self.config.expiration_delta()) exp = datetime.utcnow() + delta a...
java
public static double[][] readFromFile(String filePath) { double[][] weights; Vector<double[]> listOfWeights = new Vector<>(); try { // Open the file FileInputStream fis = new FileInputStream(filePath); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr...
java
void clear() { documents_.clear(); composite_.clear(); if (centroid_ != null) centroid_.clear(); if (sectioned_clusters_ != null) sectioned_clusters_.clear(); sectioned_gain_ = 0.0; }
python
def load_flag_values(self, flags=None): """Load flag values given from command line flags. Args: flags: An argparse Namespace containing the command line flags. """ if flags is None: flags = self._flags for keyval in flags.config_value: k, v = keyval.split('=', 1) v = self._...
java
protected static <O> void initializeMatrices(MatrixParadigm mat, ArrayModifiableDBIDs prots, DistanceQuery<O> dq) { final DBIDArrayIter ix = mat.ix, iy = mat.iy; final double[] distances = mat.matrix; int pos = 0; for(ix.seek(0); ix.valid(); ix.advance()) { for(iy.seek(0); iy.getOffset() < ix.getO...
python
def file_length(in_file): '''Function to return the length of a file.''' fid = open(in_file) data = fid.readlines() fid.close() return len(data)
python
def publication_info(self, key, value): """Populate the ``publication_info`` key.""" def _get_cnum(value): w_value = force_single_element(value.get('w', '')) normalized_w_value = w_value.replace('/', '-').upper() return normalized_w_value def _get_material(value): schema = ...
java
public Mono<Response<ConfigurationSetting>> updateSetting(ConfigurationSetting setting) { // Validate that setting and key is not null. The key is used in the service URL so it cannot be null. validateSetting(setting); String etag = setting.etag() == null ? ETAG_ANY : setting.etag(); r...
python
def num_qubits(self) -> Optional[int]: """Returns number of qubits in the domain if known, None if unknown.""" if not self: return None any_gate = next(iter(self)) return any_gate.num_qubits()
java
public void encodeUnsignedInteger(int n) throws IOException { if (n < 0) { throw new UnsupportedOperationException(); } if (n < 128) { // write byte as is encode(n); } else { final int n7BitBlocks = MethodsBag.numberOf7BitBlocksToRepresent(n); switch (n7BitBlocks) { case 5: encode(128 | ...
java
public void paint(Paintable paintable, Object group, MapContext context) { // Group for objects in raster space context.getRasterContext().drawGroup(null, mapWidget.getGroup(RenderGroup.RASTER), mapWidget.getMapModel().getMapView() .getPanToViewTranslation()); // Group for objects in vector space cont...
java
public static String convert32(String s) { try { byte[] bytes = s.getBytes(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(bytes); bytes = md.digest(); int j = bytes.length; char[] chars = new char[j * 2]; ...
python
def get_colr(txt, argd): """ Return a Colr instance based on user args. """ fore = parse_colr_arg( get_name_arg(argd, '--fore', 'FORE', default=None), rgb_mode=argd['--truecolor'], ) back = parse_colr_arg( get_name_arg(argd, '--back', 'BACK', default=None), rgb_mode=argd[...
python
def afw_word_acceptance(afw: dict, word: list) -> bool: """ Checks if a **word** is accepted by input AFW, returning True/False. The word w is accepted by a AFW if exists at least an accepting run on w. A run for AFWs is a tree and an alternating automaton can have multiple runs on a given inpu...
java
public final boolean warmStarted() { final String methodName = "warmStarted"; if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this, cclass, methodName); boolean isWarmStarted = false; if (objectMana...
java
public static PathFragment[] from(Filter... filters) { PathFragment[] ret = new PathFragment[filters.length]; Arrays.setAll(ret, (i) -> new PathFragment(filters[i])); return ret; }
python
def bed(args): """ %prog bed frgscffile Convert the frgscf posmap file to bed format. """ p = OptionParser(bed.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) frgscffile, = args bedfile = frgscffile.rsplit(".", 1)[0] + ".bed" fw...
java
protected void initSettings(Element root, CmsXmlContentDefinition contentDefinition) { Iterator<Element> itProperties = CmsXmlGenericWrapper.elementIterator(root, APPINFO_SETTING); while (itProperties.hasNext()) { Element element = itProperties.next(); CmsXmlContentProperty sett...
python
def report_stats(self, payload, is_retry=False): """ Send data to graphite host :param payload: Data to send to graphite """ if self.debug: if self.pickle_proto: print "reporting pickled stats" else: print "reporting stats ...
java
@TCB static String stripBannedCodeunits(String s) { int safeLimit = longestPrefixOfGoodCodeunits(s); if (safeLimit < 0) { return s; } StringBuilder sb = new StringBuilder(s); stripBannedCodeunits(sb, safeLimit); return sb.toString(); }
java
public O setParallelism(int dop) { if(dop < 1) { throw new IllegalArgumentException("The parallelism of an operator must be at least 1."); } this.dop = dop; @SuppressWarnings("unchecked") O returnType = (O) this; return returnType; }
python
def reboot(self, subid, params=None): ''' /v1/server/reboot POST - account Reboot a virtual machine. This is a hard reboot (basically, unplugging the machine). Link: https://www.vultr.com/api/#server_reboot ''' params = update_params(params, {'SUBID': subid}) ...
java
protected static String intsToCommaDelimitedString(int[] ints) { if (ints == null) { return ""; } StringBuilder result = new StringBuilder(); for (int i = 0; i < ints.length; i++) { result.append(ints[i]); if (i < (ints.length - 1)) { ...
python
def read_git_commit_timestamp(repo_path=None): """Obtain the timestamp from the current head commit of a Git repository. Parameters ---------- repo_path : `str`, optional Path to the Git repository. Leave as `None` to use the current working directory. Returns ------- commi...
java
public String getID() { byte[] genBytes = new byte[_byteArraySize]; synchronized(_random) { _random.nextBytes(genBytes); } String id = convertSessionIdBytesToSessionId(genBytes, _sessionIDLength); if (logger.isLoggable(Level.FINE)) { logger.logp(Level.FINE...
python
def iter_child_nodes(node): """Iterate over all child nodes or a node.""" for name, field in iter_fields(node): if isinstance(field, AST): yield field elif isinstance(field, list): for item in field: if isinstance(item, AST): yield item
java
@Override public UpdateServicePrimaryTaskSetResult updateServicePrimaryTaskSet(UpdateServicePrimaryTaskSetRequest request) { request = beforeClientExecution(request); return executeUpdateServicePrimaryTaskSet(request); }
java
private void read_env() { String env; try { if ((env = System.getProperty("TANGO_HOST")) == null) { if ((env = System.getenv("TANGO_HOST")) == null) { Except.throw_connection_failed("TangoApi_TANGO_HOST_NOT_SET", "Property \"TANGO_HOST\" not exported", "TangoDs.Util.read_env()...
python
def check_nonbond(molecule, thresholds): """Check whether all nonbonded atoms are well separated. If a nonbond atom pair is found that has an interatomic distance below the given thresholds. The thresholds dictionary has the following format: {frozenset([atom_number1, atom_number2]): distance}...
python
async def unixlisten(path, onlink): ''' Start an PF_UNIX server listening on the given path. ''' info = {'path': path, 'unix': True} async def onconn(reader, writer): link = await Link.anit(reader, writer, info=info) link.schedCoro(onlink(link)) return await asyncio.start_unix_se...
python
def read_feather(cls, path, columns=None, use_threads=True): """Read a pandas.DataFrame from Feather format. Ray DataFrame only supports pyarrow engine for now. Args: path: The filepath of the feather file. We only support local files for now. mu...
python
def suggest_charges(self, tolerance=0.1): """ Suggest possible charges for defects to computee based on proximity of known transitions from entires to VBM and CBM Args: tolerance (float): tolerance with respect to the VBM and CBM to ` continue to...
java
private File newSubdirectory(File parentDirectory, String path) { File dir = new File(parentDirectory, path); if (!dir.exists()) { dir.mkdirs(); } return dir; }
java
public static String formatDateRange(Context context, ReadablePartial start, ReadablePartial end, int flags) { return formatDateRange(context, toMillis(start), toMillis(end), flags); }
python
def get_available_mfds(): ''' Returns an ordered dictionary with the available GSIM classes keyed by class name ''' mfds = {} for fname in os.listdir(os.path.dirname(__file__)): if fname.endswith('.py'): modname, _ext = os.path.splitext(fname) mod = importlib.impo...
python
async def ResolveCharms(self, references): ''' references : typing.Sequence[str] Returns -> typing.Sequence[~ResolveCharmResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='ResolveCharms', ...
java
public static JCGLFramebufferStatus framebufferStatusFromGL( final int status) { switch (status) { case GL.GL_FRAMEBUFFER_COMPLETE: return JCGLFramebufferStatus.FRAMEBUFFER_STATUS_COMPLETE; case GL.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: return JCGLFramebufferStatus .FRAMEB...
python
def get_callable_name(c): """ Get a human-friendly name for the given callable. :param c: The callable to get the name for :type c: callable :rtype: unicode """ if hasattr(c, 'name'): return six.text_type(c.name) elif hasattr(c, '__name__'): return six.text_type(c.__name__) ...
java
public Observable<Void> deleteAsync(String jobId, JobDeleteOptions jobDeleteOptions) { return deleteWithServiceResponseAsync(jobId, jobDeleteOptions).map(new Func1<ServiceResponseWithHeaders<Void, JobDeleteHeaders>, Void>() { @Override public Void call(ServiceResponseWithHeaders<Void, Jo...
python
def from_params(cls, params: Params, instances: Iterable['adi.Instance'] = None): # type: ignore """ There are two possible ways to build a vocabulary; from a collection of instances, using :func:`Vocabulary.from_instances`, or from a pre-saved vocabulary, using :func:`Vocabulary.from_f...
java
private static List<byte[]> parsePrivateKeyASN1(ByteBuffer byteBuffer) { final List<byte[]> collection = new ArrayList<byte[]>(); while (byteBuffer.hasRemaining()) { byte type = byteBuffer.get(); int length = UnsignedBytes.toInt(byteBuffer.get()); if ((length & 0x80) != 0) { int number...
python
def build_backend(tasks, default_host=('127.0.0.1', DEFAULT_PORT), *args, **kw): """ Most of these args are passed directly to BackEnd(). However, default_host is used a bit differently. It should be a (host, port) pair, and may be overridden with cmdline args: file.py localho...
java
@NotNull @ObjectiveCName("addPreferredLanguage:") public ConfigurationBuilder addPreferredLanguage(String language) { if (!preferredLanguages.contains(language)) { preferredLanguages.add(language); } return this; }
python
def getElementsByTagName(self, tagName, root='root', useIndex=True): ''' getElementsByTagName - Searches and returns all elements with a specific tag name. @param tagName <lowercase str> - A lowercase string of the tag name. @param root <AdvancedTag/'...
python
def nvmlDeviceSetPersistenceMode(handle, mode): r""" /** * Set the persistence mode for the device. * * For all products. * For Linux only. * Requires root/admin permissions. * * The persistence mode determines whether the GPU driver software is torn down after the last client...
java
private void handleExceptions(Subroutine subroutine, InstructionHandle pei, BasicBlock etb) { etb.setExceptionThrower(pei); // Remember whether or not a universal exception handler // is reachable. If so, then we know that exceptions raised // at this instruction cannot propagate out of...
java
public Stack withStackErrors(StackError... stackErrors) { if (this.stackErrors == null) { setStackErrors(new java.util.ArrayList<StackError>(stackErrors.length)); } for (StackError ele : stackErrors) { this.stackErrors.add(ele); } return this; }
java
public void marshall(CreateLicenseConfigurationRequest createLicenseConfigurationRequest, ProtocolMarshaller protocolMarshaller) { if (createLicenseConfigurationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocol...
python
def extract_examples_from_readme_rst(indent=' '): """Extract examples from this project's README.rst file. Parameters ---------- indent: str Prepend each line with this string. Should contain some number of spaces. Returns ------- str The examples. Notes ----- ...
java
public ResourceGroupInner patch(String resourceGroupName, ResourceGroupInner parameters) { return patchWithServiceResponseAsync(resourceGroupName, parameters).toBlocking().single().body(); }
python
def dot(self, other): """Calculates the dot product of this vector and another vector.""" dot_product = 0 a = self.elements b = other.elements a_len = len(a) b_len = len(b) i = j = 0 while i < a_len and j < b_len: a_val = a[i] b_va...
java
@Override protected void configureCamera(CameraDevice device, CameraCharacteristics characteristics, CaptureRequest.Builder captureRequestBuilder) { captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO); captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, ...
python
def average_cq(seq, efficiency=1.0): """Given a set of Cq values, return the Cq value that represents the average expression level of the input. The intent is to average the expression levels of the samples, since the average of Cq values is not biologically meaningful. :param iterable seq: A sequ...
python
def _format(val, valtype, floatfmt, missingval="", has_invisible=True): """Format a value accoding to its type. Unicode is supported: >>> hrow = ['\u0431\u0443\u043a\u0432\u0430', '\u0446\u0438\u0444\u0440\u0430'] ; \ tbl = [['\u0430\u0437', 2], ['\u0431\u0443\u043a\u0438', 4]] ; \ good_re...
python
def list_roles(self): """Simplified version of get_roles that returns a dict of just name: id for the roles""" json_resp = self.get_roles() temp_dict = {} for item in json_resp: temp_dict[item["name"]] = item["id"] return temp_dict
python
def cmd(tgt, fun, arg=(), timeout=None, tgt_type='glob', kwarg=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Execute a singl...
java
public static <T> ISeq<T> front( final Seq<? extends T> set, final Comparator<? super T> dominance ) { final MSeq<T> front = MSeq.of(set); int n = front.size(); int i = 0; while (i < n) { int j = i + 1; while (j < n) { if (dominance.compare(front.get(i), front.get(j)) > 0) { --n; front...
java
public void dump() { Datum<L, F> allFeatures = new BasicDatum<L, F>(features(), (L)null); justificationOf(allFeatures); }
java
static FileInputStream createFileInputStream(final File file) throws IOException { try { FileInputStream fs = getInstance().doPrivileged( new PrivilegedExceptionAction<FileInputStream>() { public FileInputStream run() throws IOException { return new FileInputStream(file); } } ); ...
java
public GetItemRequest withExpressionAttributeNames(java.util.Map<String, String> expressionAttributeNames) { setExpressionAttributeNames(expressionAttributeNames); return this; }
python
def create(cls, fqdn, flags, algorithm, public_key): """Create a dnssec key.""" fqdn = fqdn.lower() params = { 'flags': flags, 'algorithm': algorithm, 'public_key': public_key, } result = cls.call('domain.dnssec.create', fqdn, params) ...
python
def bind(self, **kwargs): """Subscribes to events or to :class:`~pydispatch.properties.Property` updates Keyword arguments are used with the Event or Property names as keys and the callbacks as values:: class Foo(Dispatcher): name = Property() foo = Foo...
python
def submain(p): """ completly set-up a package in the target dir (using cookie cutter) """ parser = argparse.ArgumentParser(description='Bootstrap a Python Package with Love.') parser.add_argument('name', metavar='name', type=str, nargs='?', help='a potential packag...
java
@Override public Collection<AgentProjectInfo> collectDependencies(String rootDirectory) { Collection<AgentProjectInfo> projects = new ArrayList<>(); if (!this.isMavenExist(rootDirectory)) { logger.warn("Please install maven"); } else { if (runPreStep) { ...
python
def delete_host_from_segment(ipaddress, networkaddress, auth, url): '''Function to abstract ''' host_id = get_host_id(ipaddress, networkaddress, auth, url) remove_scope_ip(host_id, auth.creds, auth.url)
python
def float_str(value, order="pprpr", size=[4, 5, 3, 6, 4], after=False, max_denominator=1000000): """ Pretty string from int/float. "Almost" automatic string formatter for integer fractions, fractions of :math:`\pi` and float numbers with small number of digits. Outputs a representation among `...
python
def _update_shared_response(X, S, W, features): """Update the shared response `R`. Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, timepoints] Each element in the list contains the fMRI data for alignment of one subject. S : ...
java
public static synchronized IClient getNamedClient(String name, Class<? extends IClientConfig> configClass) { if (simpleClientMap.get(name) != null) { return simpleClientMap.get(name); } try { return createNamedClient(name, configClass); } catch (ClientException e) { ...
python
def _get_tax(self, order_book_id, _, cost_money): """ 港交所收费项目繁多,按照如下逻辑计算税费: 1. 税费比例为 0.11%,不足 1 元按 1 元记,四舍五入保留两位小数(包括印花税、交易征费、交易系统使用费)。 2,五元固定费用(包括卖方收取的转手纸印花税、买方收取的过户费用)。 """ instrument = Environment.get_instance().get_instrument(order_book_id) if instrument.type ...
java
@Override public DisassociateWebACLResult disassociateWebACL(DisassociateWebACLRequest request) { request = beforeClientExecution(request); return executeDisassociateWebACL(request); }
java
public synchronized void onRequestFailed(Throwable reason) { executing.decrement(); failed.increment(); lastFailureReason = (reason == null) ? null : reason.getClass() .getName() + ": " + reason.getMessage(); }
python
def bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'): """Binds the symbols to construct executors for both two modules. This is necessary before one can perform computation with the SVRGModule. ...
python
def find_keys(self, regex, bucket_name=None): """Finds a list of S3 keys matching the passed regex Given a regular expression, this method searches the S3 bucket for matching keys, and returns an array of strings for matched keys, an empty array if non are found. :param regex: ...
java
@Override public final void configureThresholdEvaluatorBuilder(final ThresholdsEvaluatorBuilder thrb, final ICommandLine cl) throws BadThresholdException { thrb.withLegacyThreshold("time", null, cl.getOptionValue("warning"), cl.getOptionValue("critical")); if (cl.hasOption("regex")) { if...
java
protected CheckGroup<T> newCheckGroup(final String id, final IModel<? extends Collection<T>> model) { final CheckGroup<T> checkGroup = ComponentFactory.newCheckGroup(id, model); checkGroup.add(new AjaxFormChoiceComponentUpdatingBehavior() { /** The serialVersionUID. */ private static final long serialVer...
python
def get_residue_annotations(self, seq_resnum, seqprop=None, structprop=None, chain_id=None, use_representatives=False): """Get all residue-level annotations stored in the SeqProp ``letter_annotations`` field for a given residue number. Uses the representative sequence, s...
python
def idsKEGG(organism): """ Uses KEGG to retrieve all ids for a given KEGG organism :param organism: an organism as listed in organismsKEGG() :returns: a Pandas dataframe of with 'gene_name' and 'KEGGid'. """ ORG=urlopen("http://rest.kegg.jp/list/"+organism).read() ORG=ORG.split("\n") ...
java
public List<CmsRewriteAlias> getRewriteAliases(CmsDbContext dbc, CmsRewriteAliasFilter filter) throws CmsException { return getVfsDriver(dbc).readRewriteAliases(dbc, filter); }
java
@Override public Promise waitForServices(long timeoutMillis, Collection<String> services) { if (services == null || services.isEmpty() || isServicesOnline(services)) { return Promise.resolve(); } Promise promise = new Promise(); long timeoutAt; if (timeoutMillis > 0) { timeoutAt = System.currentTimeMil...
java
protected int getIntSetting(String name, int defaultValue) throws IllegalArgumentException { if (settings.containsKey(name)) { String value = settings.get(name).toString(); try { return Integer.parseInt(value); } catch (Exception e) { throw ne...
python
def beacon(config): ''' Watch for changes on network settings By default, the beacon will emit when there is a value change on one of the settings on watch. The config also support the onvalue parameter for each setting, which instruct the beacon to only emit if the setting changed to the value...
java
public final void bindUntilJavaShutdown(Duration timeout, @Nullable Consumer<DisposableServer> onStart) { Objects.requireNonNull(timeout, "timeout"); DisposableServer facade = bindNow(); Objects.requireNonNull(facade, "facade"); if (onStart != null) { onStart.accept(facade); } Runtime.getRuntime() ...