language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private void DrawPrimitive( DrawCuboid c, World w ) throws Exception { XMLBlockState blockType = new XMLBlockState(c.getType(), c.getColour(), c.getFace(), c.getVariant()); if (!blockType.isValid()) throw new Exception("Unrecogised item type: "+c.getType().value()); int x1 = Mat...
python
def define_empty_source_parallel_buckets(max_seq_len_target: int, bucket_width: int = 10) -> List[Tuple[int, int]]: """ Returns (source, target) buckets up to (None, max_seq_len_target). The source is empty since it is supposed to not contain data that can be bucketi...
python
def append(self, name): """If name is not in the map, append it with an empty id range set.""" if not isinstance(name, str): raise TypeError( "argument 'name' must be a string, not {}".format( name.__class__.__name__ ) ...
java
public LocalTrustGraphNode addNode(final TrustGraphNodeId nodeId) { final LocalTrustGraphNode node = createNode(nodeId); addNode(node); return node; }
python
def selected_subcategory(self): """Obtain the subcategory selected by user. :returns: Metadata of the selected subcategory. :rtype: dict, None """ item = self.lstSubcategories.currentItem() try: return definition(item.data(QtCore.Qt.UserRole)) except ...
python
def parse(readDataInstance): """ Returns a new L{TLSDirectory64} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object containing data to create a new L{TLSDirectory64} object. @rtype: L{TLSDirectory64} @return: A new ...
java
public static Method getAccessibleMethod(final Class<?> cls, final String methodName, final Class<?>... parameterTypes) { try { return getAccessibleMethod(cls.getMethod(methodName, parameterTypes)); } catch (final NoSuchMethodException e) { return ...
java
@Override public List<String> getNodeNames(CommandContext ctx, OperationRequestAddress prefix) { ModelControllerClient client = ctx.getModelControllerClient(); if(client == null) { return Collections.emptyList(); } if(prefix.isEmpty()) { throw new IllegalArg...
java
public static String getFullAtomSequence(List<Group> groups, Map<Integer, Integer> positionIndex, boolean isNucleotideChain){ StringBuffer sequence = new StringBuffer() ; int seqIndex = 0; // track sequence.length() for ( int i=0 ; i< groups.size(); i++){ Group g = groups.get(i); if ( g instanceof AminoAc...
java
protected void appendWhereClause(ClassDescriptor cld, boolean useLocking, StringBuffer stmt) { FieldDescriptor[] pkFields = cld.getPkFields(); FieldDescriptor[] fields; fields = pkFields; if(useLocking) { FieldDescriptor[] lockingFields = cld.getLockingFi...
python
def run(self, **kwargs): """Run method iterates through triple maps and calls the execute method""" if 'timestamp' not in kwargs: kwargs['timestamp'] = datetime.datetime.utcnow().isoformat() if 'version' not in kwargs: kwargs['version'] = "Not Defined" #bibcat.__v...
java
@Beta public static <K, V> Map<K, V> fromDictionary(Dictionary<K, V> dictionary) { checkArgument(dictionary != null, "Expected non-null dictionary"); ImmutableMap.Builder<K, V> builder = ImmutableMap.builder(); for (Enumeration<K> keys = dictionary.keys(); keys.hasMoreElements(); ) { ...
java
public static Boolean getShouldDistribute(DistributableWork work) { if (work != null && work instanceof WorkContextProvider) { List<WorkContext> contexts = ((WorkContextProvider)work).getWorkContexts(); if (contexts != null) { for (WorkContext wc : contexts) ...
java
public static File zip(File zipFile, Charset charset, boolean withSrcDir, File... srcFiles) throws UtilException { validateFiles(zipFile, srcFiles); try (ZipOutputStream out = getZipOutputStream(zipFile, charset)) { String srcRootDir; for (File srcFile : srcFiles) { if(null == srcFile) { cont...
python
def images(self): ''' List of URLs of images on the page. ''' if not getattr(self, '_images', False): self._images = [ page['imageinfo'][0]['url'] for page in self.__continued_query({ 'generator': 'images', 'gimlimit': 'max', 'prop': 'imageinfo', ...
python
def filter(cls, parent=None, **filters): """ Gets all resources of the given type and parent (if provided) which match the given filters. This will trigger an api GET request. :param parent ResourceBase: the parent of the resource - used for nesting the request url, optional :par...
java
@SuppressWarnings("unchecked") public EList<IfcCurveStyleFontPattern> getPatternList() { return (EList<IfcCurveStyleFontPattern>) eGet(Ifc2x3tc1Package.Literals.IFC_CURVE_STYLE_FONT__PATTERN_LIST, true); }
python
def vxvyvz_to_vrpmllpmbb(vx,vy,vz,l,b,d,XYZ=False,degree=False): """ NAME: vxvyvz_to_vrpmllpmbb PURPOSE: Transform velocities in the rectangular Galactic coordinate frame to the spherical Galactic coordinate frame (can take vector inputs) INPUT: vx - velocity towards the Galact...
python
def _create_messages(self, names, data, isDms=False): """ Creates object of arrays of messages from each json file specified by the names or ids :param [str] names: names of each group of messages :param [object] data: array of objects detailing where to get the messages from in ...
java
private void readQueryGroup(LineNumberReader reader, String groupId) throws IOException { String line = ""; while (!(line = reader.readLine()).equals(END_COLLECTION_SYMBOL)) { if (isCommentLine(line) || line.isEmpty()) { continue; // skip comment lines } ...
java
public static void main(String[] args) throws InterruptedException { ExampleUtils.fillManagerWithSimons(100000); final ExecutorService executorService = Executors.newFixedThreadPool(1000); StopwatchSample[] results = BenchmarkUtils.run(1, 2, new BenchmarkUtils.Task("1") { @Override public void perform(...
java
public String formatThroughput(int theNumOperations, TimeUnit theUnit) { double throughput = getThroughput(theNumOperations, theUnit); return new DecimalFormat("0.0").format(throughput); }
python
def get_sorted_series_files(self, startpath="", series_number=None, return_files_with_info=False, sort_keys="SliceLocation", return_files=True, remove_doubled_slice_locations=True): """ Function returns sorted list of dicom files. File paths are organized by Serie...
python
def _overapprox(self): """ The method extracts a model corresponding to an over-approximation of an MCS, i.e. it is the model of the hard part of the formula (the corresponding oracle call is made in :func:`compute`). Here, the set of selectors is divided into tw...
java
private Object readResolve() { Chronology base = getBase(); return base == null ? getInstance(DateTimeZone.UTC, getMinimumDaysInFirstWeek()) : getInstance(base.getZone(), getMinimumDaysInFirstWeek()); }
python
def _get_symbol_index(stroke_id_needle, segmentation): """ Parameters ---------- stroke_id_needle : int Identifier for the stroke of which the symbol should get found. segmentation : list of lists of integers An ordered segmentation of strokes to symbols. Returns ------- ...
python
def declare_directory(self, value): # type: (MutableMapping) -> ProvEntity """Register any nested files/directories.""" # FIXME: Calculate a hash-like identifier for directory # so we get same value if it's the same filenames/hashes # in a different location. # For now, mint a n...
java
private boolean checkValueAndNext(StringTokenizer st, String token) throws InvalidDateException { if (!st.hasMoreTokens()) { return false; } String t = st.nextToken(); if (!t.equals(token)) { throw new InvalidDateException("Unexpected: " + t); } if (!st.hasMoreTokens(...
java
public static int getSystemPort(String portIdentifier) { int defaultPort = 0; if (portIdentifier.compareTo(Constants.SYS_API_PORT) == 0) { defaultPort = Constants.DEFAULT_API_PORT; } else if (portIdentifier.compareTo(Constants.SYS_DB_PORT) == 0) { defaultPort = Constants...
java
public final void destroy() throws JMException { synchronized (mBeanHandles) { List<JMException> exceptions = new ArrayList<JMException>(); List<MBeanHandle> unregistered = new ArrayList<MBeanHandle>(); for (MBeanHandle handle : mBeanHandles) { try { ...
python
def get_data(self, size=None, addr=None): ''' Gets data for incoming stream ''' # readback memory offset if addr is None: addr = self._mem_bytes if size and self._mem_bytes < size: raise ValueError('Size is too big') if size is None: ...
python
def delete_tags(filesystemid, tags, keyid=None, key=None, profile=None, region=None, **kwargs): ''' Deletes the specified tags from a file system. filesystemid (string) - ID of the file system for whose ...
java
private boolean validate(final String realName, final String address, final Problems problems, final String compName) { final String[] nameAndHost = address.split("@"); if (nameAndHost.length == 1 && nameAndHost[0].contains("@")) { problems.add(ValidationBundle.getMessage(EmailAddressValidator.class, "EMAIL_MISS...
python
def last_modified(self): '''Read the last-modified header as a datetime, if present.''' lm = self.response.headers.get('last-modified', None) return datetime.strptime(lm, '%a, %d %b %Y %H:%M:%S GMT') if lm \ else None
python
def addItem(self, item): """Adds an item if the tree is mutable""" try: self.tree.addItem(item) except AttributeError, e: raise VersionError('Saved versions are immutable')
java
public void setupSFields() { this.getRecord(KeyInfo.KEY_INFO_FILE).getField(KeyInfo.KEY_NAME).setupDefaultView(this.getNextLocation(ScreenConstants.NEXT_LOGICAL, ScreenConstants.ANCHOR_DEFAULT), this, ScreenConstants.DEFAULT_DISPLAY); this.getRecord(KeyInfo.KEY_INFO_FILE).getField(KeyInfo.KEY_TYPE)....
java
@Override public void removeTextNode(String key) { ITextNode textNode = getTextNode(key); if (textNode != null) { removeTextNodes(new ITextNode[] {textNode}); } }
python
def extract_ascii_strings(cls, process, minSize = 4, maxSize = 1024): """ Extract ASCII strings from the process memory. @type process: L{Process} @param process: Process to search. @type minSize: int @param minSize: (Optional) Minimum size of the strings to search fo...
python
def query(ra ,dec, rad=0.1, query=None): """Query the CADC TAP service to determine the list of images for the NewHorizons Search. Things to determine: a- Images to have the reference subtracted from. b- Image to use as the 'REFERENCE' image. c- Images to be used for input into the reference image L...
python
def describe_handler(h): """Yield one or more lines describing the logging handler `h`.""" t = h.__class__ # using type() breaks in Python <= 2.6 format = handler_formats.get(t) if format is not None: yield format % h.__dict__ else: yield repr(h) level = getattr(h, 'level', logg...
python
def AsociarLiquidacionSecundariaAContrato(self, coe=None, nro_contrato=None, cuit_comprador=None, cuit_vendedor=None, cuit_corredor=None, cod_grano=No...
java
public void drawRectangle(int x, int y, int z, int width, int height, int color, int alpha) { drawRectangle(x, y, z, width, height, color, alpha, true); }
java
public static String applyUriReplace(String uriSource, Configuration conf) { if (uriSource == null) return null; String[] uriReplace = conf.getStrings(OUTPUT_URI_REPLACE); if (uriReplace == null) return uriSource; for (int i = 0; i < uriReplace.length - 1; i += 2) { String re...
python
def set_signal_handlers(self): '''Set some signal handlers. These react reasonably to shutdown requests, and keep the logging child alive. ''' def handler(f): def wrapper(signum, backtrace): return f() return wrapper self.old_sig...
java
public static ExpectedCondition<Boolean> javaScriptThrowsNoExceptions(final String javaScript) { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver driver) { try { ((JavascriptExecutor) driver).executeScript(javaScript); return true; } ...
python
def only(name, hostnames): ''' Ensure that only the given hostnames are associated with the given IP address. .. versionadded:: 2016.3.0 name The IP address to associate with the given hostnames. hostnames Either a single hostname or a list of hostnames to associate wi...
python
def convert_tensor(input_, device=None, non_blocking=False): """Move tensors to relevant device.""" def _func(tensor): return tensor.to(device=device, non_blocking=non_blocking) if device else tensor return apply_to_tensor(input_, _func)
python
def plot_moist_adiabats(self, p=None, thetaes=None, **kwargs): r'''Plot moist adiabats. Adds saturated pseudo-adiabats (lines of constant equivalent potential temperature) to the plot. The default style of these lines is dashed blue lines with an alpha value of 0.5. These can be overrid...
python
def image_embedding(images, model_fn=resnet_v1_152, trainable=True, is_training=True, weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-5, batch_norm_scale=True, ...
python
def class_to_value(axis, ufo_class): """ >>> class_to_value('wdth', 7) 125 """ if axis == "wght": # 600.0 => 600, 250 => 250 return int(ufo_class) elif axis == "wdth": return WIDTH_CLASS_TO_VALUE[int(ufo_class)] raise NotImplementedError
java
static Codec<NamingMessage> createRegistryCodec(final IdentifierFactory factory) { final Map<Class<? extends NamingMessage>, Codec<? extends NamingMessage>> clazzToCodecMap = new HashMap<>(); clazzToCodecMap.put(NamingRegisterRequest.class, new NamingRegisterRequestCodec(factory)); clazzToCodecMap.p...
python
def create_gist(self, description, files, public=True): """Create a new gist. If no login was provided, it will be anonymous. :param str description: (required), description of gist :param dict files: (required), file names with associated dictionaries for content, e.g. ``{...
python
def build_configuration_parameters(app): """Create documentation for configuration parameters.""" env = Environment(loader=FileSystemLoader("{0}/_data_templates".format(BASEPATH))) template_file = env.get_template("configuration-parameters.j2") data = {} data["schema"] = Config.schema() rendered...
java
public void setThreshold(final double THRESHOLD) { if (Double.compare(THRESHOLD, minValue) >= 0 && Double.compare(THRESHOLD, maxValue) <= 0) { threshold = THRESHOLD; } else { if (THRESHOLD < niceMinValue) { threshold = niceMinValue; } if (...
java
public static <T extends CharSequence> Collection<T> removeBlank(Collection<T> collection) { return filter(collection, new Filter<T>() { @Override public boolean accept(T t) { return false == StrUtil.isBlank(t); } }); }
python
def circuit_diagram_info(val: Any, args: Optional[CircuitDiagramInfoArgs] = None, default=RaiseTypeErrorIfNotProvided): """Requests information on drawing an operation in a circuit diagram. Calls _circuit_diagram_info_ on `val`. If `val` doesn't have _circu...
java
private final void handleHttpWorkerResponse( ResponseOnSingeRequest respOnSingleReq) throws Exception { // Successful response from GenericAsyncHttpWorker // Jeff 20310411: use generic response String responseContent = respOnSingleReq.getResponseBody(); response.setResponse...
python
def remove(self, node, dirty=True): """Remove the given child node. Args: node (gkeepapi.Node): Node to remove. dirty (bool): Whether this node should be marked dirty. """ if node.id in self._children: self._children[node.id].parent = None ...
java
public ServiceFuture<ExpressRouteConnectionInner> createOrUpdateAsync(String resourceGroupName, String expressRouteGatewayName, String connectionName, ExpressRouteConnectionInner putExpressRouteConnectionParameters, final ServiceCallback<ExpressRouteConnectionInner> serviceCallback) { return ServiceFuture.fromR...
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SimpleExpressionsPackage.NUMBER_LITERAL__VALUE: setValue((Integer)newValue); return; } super.eSet(featureID, newValue); }
python
def remote_evb_mode_uneq_store(self, remote_evb_mode): """Saves the EVB mode, if it is not the same as stored. """ if remote_evb_mode != self.remote_evb_mode: self.remote_evb_mode = remote_evb_mode return True return False
python
def exportFile(self, jobStoreFileID, dstUrl): """ Exports file to destination pointed at by the destination URL. Refer to :meth:`.AbstractJobStore.importFile` documentation for currently supported URL schemes. Note that the helper method _exportFile is used to read from the source and ...
java
public SelectionCriteria[] getCriterias() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getCriterias"); SelectionCriteria[] criterias = aiRequestedTick.getCriterias(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exi...
python
def days_range(first=None, second=None, wipe=False): """ get all days between first and second :param first: datetime, date or string :param second: datetime, date or string :param wipe: boolean, excludes first and last date from range when True. Default is False. :return: list """ _fir...
python
def _set_context(context=None, font_scale=1, rc=None): """ Set the plotting context parameters. NOTE: This is an internal method from Seaborn that is simply used to create a default aesthetic in yellowbrick. If you'd like to use these styles then import Seaborn! This affects things like the si...
python
def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue ...
python
def alternative_short_name(self, name=None, entry_name=None, limit=None, as_df=False): """Method to query :class:`.models.AlternativeShortlName` objects in database :param name: alternative short name(s) :type name: str or tuple(str) or None :param entry_name: name(s) in :class:`.model...
java
private void manageExceptions(final String method_name) throws DevFailed { if (attrval.err_list != null) { if (attrval.err_list.length > 0) { throw new WrongData(attrval.err_list); } } if (attrval.quality == AttrQuality.ATTR_INVALID) { Except.throw_wrong_data_exception("AttrQuality_ATTR_INVALID", ...
python
def _viewEntryNumber(self, ientry, select=True): """views entry #ientry. Also selects entry in listview if select=True""" # pass entry to viewer dialog self._viewing_ientry = ientry entry = self.purrer.entries[ientry] busy = BusyIndicator() self.view_entry_dialog.viewEntr...
python
def rows(self, *args) -> List[List[Well]]: """ Accessor function used to navigate through a labware by row. With indexing one can treat it as a typical python nested list. To access row A for example, simply write: labware.rows()[0]. This will output ['A1', 'A2', 'A3', 'A4'...] ...
python
def bulk_delete(handler, request): """Bulk delete items""" ids = request.GET.getall('ids') Message.delete().where(Message.id << ids).execute() raise muffin.HTTPFound(handler.url)
java
private static void generateConstructor(PrefsEntity entity, String sharedPreferenceName, String beanClassName) { MethodSpec.Builder method = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).addJavadoc("constructor\n"); method.addStatement("createPrefs()"); if (entity.isImmutablePojo()) { Immuta...
java
public void nextState(PHATInterface phatInterface) { switch (state) { case NOT_INIT: //System.out.println(getAgent().getId()+":"+getName()+"(NOT_INIT)"); /*currentState = null; if(pendingTransitions != null) { pendingTransitions.cle...
python
def pretty_print(self, printer: Optional[Printer] = None, min_width: int = 1, min_unit_width: int = 1): """ Prints the file size (and it's unit), reserving places for longer sizes and units. For example: min_unit_width = 1: 793 B 100 KB min...
java
@Override public TransportRequestOptions transportOptions(Settings settings) { return TransportRequestOptions.builder() .withType(TransportRequestOptions.Type.REG) .build(); }
python
def add(self, nb = 1, name = None, xid = None): """ Create one or many workers. """ for x in xrange(nb): self.count_lock.acquire() if self.workers >= self.max_workers: self.count_lock.release() continue self.workers += 1...
java
@Override @Deprecated public Object getFeature(String name) { throw new IllegalArgumentException(MessageFormat.format(ErrorConsts.ERR_UNKNOWN_FEATURE, new Object[] { name })); }
java
public void append(LogSegment segment) { while (true) { List<LogSegment> curr = contents.get(); List<LogSegment> updated = new ArrayList<LogSegment>(curr); updated.add(segment); if (contents.compareAndSet(curr, updated)) { return; } ...
python
def array_insert(path, *values, **kwargs): """ Insert items at a given position within an array. :param path: The path indicating where the item should be placed. The path _should_ contain the desired position :param values: Values to insert This operation is only valid in :cb_bmeth:`mutat...
java
private void cmdCancelOperationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCancelOperationActionPerformed try { monitor.cancel(); } catch (Exception e) { OptionPaneUtils.showPrettyMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } }
python
def fetch_movielens( data_home=None, indicator_features=True, genre_features=False, min_rating=0.0, download_if_missing=True, ): """ Fetch the `Movielens 100k dataset <http://grouplens.org/datasets/movielens/100k/>`_. The dataset contains 100,000 interactions from 1000 users on 1700 mov...
python
def markdown_safe(value, arg=None): """ Render markdown over a given value, optionally using varios extensions. Default extensions could be defined which MARKDOWN_EXTENSIONS option. Enables safe mode, which strips raw HTML and only returns HTML generated by markdown. :returns: A rendered markdown...
java
@Override public void taskStarting() throws RejectedExecutionException { if (suspendTranOfExecutionThread) { // Suspend whatever is currently on the thread. try { UOWManager uowManager = UOWManagerFactory.getUOWManager(); suspendedUOW = uowManager.susp...
python
def load_archive(archive_file: str, cuda_device: int = -1, overrides: str = "", weights_file: str = None) -> Archive: """ Instantiates an Archive from an archived `tar.gz` file. Parameters ---------- archive_file: ``str`` The archive file t...
java
private Object evaluateExpressionInternal(String expression, String attrName, PageContext pageContext) throws JspException { if (logger.isDebugEnabled()) logger.debug("evaluate expression=\"" + expression + "\""); Object result = null; try { VariableResol...
python
def _parse_tmx(path): """Generates examples from TMX file.""" def _get_tuv_lang(tuv): for k, v in tuv.items(): if k.endswith("}lang"): return v raise AssertionError("Language not found in `tuv` attributes.") def _get_tuv_seg(tuv): segs = tuv.findall("seg") assert len(segs) == 1, "In...
java
public boolean removeWatcher(Listener watcher) { if (watcher == null) { throw new IllegalArgumentException("Null watcher removed"); } synchronized (mutex) { AtomicBoolean removed = new AtomicBoolean(removeFromListeners(watchers, watcher)); watchedFiles.forEac...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.FONT_RESOLUTION__MET_TECH: return MET_TECH_EDEFAULT == null ? metTech != null : !MET_TECH_EDEFAULT.equals(metTech); case AfplibPackage.FONT_RESOLUTION__RPU_BASE: return RPU_BASE_EDEFAULT == null ? rPuBase != null :...
python
def get_relations(self, rel_id=None, **kwargs): """ Alias for get_elements() but filter the result by Relation :param rel_id: Id of the relation :type rel_id: Integer :return: List of elements """ return self.get_elements(Relation, elem_id=rel_id, **kwargs)
python
def generate_random_nhs_number() -> int: """ Returns a random valid NHS number, as an ``int``. """ check_digit = 10 # NHS numbers with this check digit are all invalid while check_digit == 10: digits = [random.randint(1, 9)] # don't start with a zero digits.extend([random.randint(0...
java
public static Filter<ArchivePath> includePaths(final String... paths) { return getFilterInstance(IMPL_CLASS_NAME_INCLUDE_PATHS, new Class<?>[] { String[].class }, new Object[] { paths }); }
java
public void unlockAll(int requestNumber) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "unlockAll", requestNumber); SIErrorException e = new SIErrorException( nls.getFormattedMessage("PROTOCOL_ERROR_SICO2003", null, null) ); FFDCFilter.pro...
python
def iterate(self, max_iter=150): r"""Iterate This method calls update until either convergence criteria is met or the maximum number of iterations is reached Parameters ---------- max_iter : int, optional Maximum number of iterations (default is ``150``) ...
java
public void logTaskFinished(TaskID taskId, String taskType, long finishTime, Counters counters) { if (disableHistory) { return; } JobID id = taskId.getJobID(); if (!this.jobId.equals(id)) { throw new RuntimeException("JobId from task: " + id + " does...
java
public static dnssrvrec get(nitro_service service, dnssrvrec obj) throws Exception{ options option = new options(); option.set_args(nitro_util.object_to_string_withoutquotes(obj)); dnssrvrec response = (dnssrvrec) obj.get_resource(service,option); return response; }
python
def add_redirect(self, name, proto, host_ip, host_port, guest_ip, guest_port): """Adds a new NAT port-forwarding rule. in name of type str The name of the rule. An empty name is acceptable, in which case the NAT engine auto-generates one using the other parameters. in p...
java
protected final void setResultIterator(MutableObjectIterator<E> iterator) { synchronized (this.iteratorLock) { // set the result iterator only, if no exception has occurred if (this.iteratorException == null) { this.iterator = iterator; this.iteratorLock.notifyAll(); } } }
python
def get_port_by_name(self, port_name): '''Get a port of this component by name.''' with self._mutex: for p in self.ports: if p.name == port_name: return p return None
java
@Override public RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException { if(exerciseMethod == ExerciseMethod.UPPER_BOUND_METHOD) { // Find optimal lambda GoldenSectionSearch optimizer = new GoldenSectionSearch(-1.0, 1.0); while(!optimizer.isDon...
python
def to_file(self, output_filename): '''Handles pdf and epub format. Inpute: output_filename should have the proper extension. Output: The name of the file created, or an IOError if failed''' temp_file = NamedTemporaryFile(mode="w", suffix=".md", delete=False) temp_file.write(self...