language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _flatten_fetched_fields(fields_arg): """ this method takes either a kwargs 'fields', which can be a dict : {"_id": False, "store": 1, "url": 1} or a list : ["store", "flag", "url"] and returns a tuple : ("store", "flag"). it HAS to be a tuple, so that it is not updated by the different instances ...
python
def _get_notification(self, email, token): ''' Consulta o status do pagamento ''' url = u'{notification_url}{notification_code}?email={email}&token={token}'.format( notification_url=self.notification_url, notification_code=self.notification_code, email=email, ...
python
def crl(request, pk): """ returns CRL of a CA """ authenticated = request.user.is_authenticated authenticated = authenticated() if callable(authenticated) else authenticated if app_settings.CRL_PROTECTED and not authenticated: return HttpResponse(_('Forbidden'), ...
python
def paper_format_efficiency_gain_df(eff_gain_df): """Transform efficiency gain data frames output by nestcheck into the format shown in the dynamic nested sampling paper (Higson et al. 2019). Parameters ---------- eff_gain_df: pandas DataFrame DataFrame of the from produced by efficiency_ga...
python
def sources(self): """A tuple containing the names of the Class sources for this Slot. The Python equivalent of the CLIPS slot-sources function. """ data = clips.data.DataObject(self._env) lib.EnvSlotSources(self._env, self._cls, self._name, data.byref) return tuple(d...
python
def extraction(event_collection, timeframe=None, timezone=None, filters=None, latest=None, email=None, property_names=None): """ Performs a data extraction Returns either a JSON object of events or a response indicating an email will be sent to you with data. :param event_collection: s...
python
def verify_headers(self, check_presence=True, **kwargs): """ Check that a set of particular header claim are present and has specific values :param kwargs: The claim/value sets as a dictionary :return: True if the claim that appears in the header has the prescribed v...
java
public java.util.List<DelegationSet> getDelegationSets() { if (delegationSets == null) { delegationSets = new com.amazonaws.internal.SdkInternalList<DelegationSet>(); } return delegationSets; }
python
def format_value(self, value, padding): """Get padding adjusting for negative values.""" # padding = padding - 1 if value < 0 and padding > 0 else padding # prefix = '-' if value < 0 else '' if padding: return "{:0{pad}d}".format(value, pad=padding) else: ...
java
private float[] sobel(int x, int y) { int v00 = 0, v01 = 0, v02 = 0, v10 = 0, v12 = 0, v20 = 0, v21 = 0, v22 = 0; int x0 = x - 1, x1 = x, x2 = x + 1; int y0 = y - 1, y1 = y, y2 = y + 1; if (x0 < 0) x0 = 0; if (y0 < 0) y0 = 0; if (x2 >= width) x2 = width - 1; if (y2 >= height) y2 =...
java
public static void runCommand(String[] cmdArray, File logFile, File dir) { Process proc = System.runProcess(cmdArray, logFile, dir); if (proc.exitValue() != 0) { throw new RuntimeException("Command failed with exit code " + proc.exitValue() + ": " + System.cmdToString(cmd...
python
def unique(seq): """Return the unique values in a sequence. Parameters ---------- seq : sequence Sequence with (possibly duplicate) elements. Returns ------- unique : list Unique elements of ``seq``. Order is guaranteed to be the same as in seq. Examples --...
java
private void addQueryParametersFromManager(IFilterCriteriaManager manager) { Map<FilterCriteriaType, IFilterCriteria> criterias = manager.getFilterCriterias(); for (FilterCriteriaType type : criterias.keySet()) { IFilterCriteria criteria = criterias.get(type); if (criteria == nul...
python
def sequential_map(task, args, message, nargs=None): """ Helper to map a function over a sequence of inputs, sequentially, with progress meter. :param client: IPython.parallel.Client instance :param task: Function :param args: Must be a list of tuples of arguments that the task function will be mapp...
java
public HttpResponseMessageImpl getResponse(HttpOutboundServiceContext hsc) { HttpResponseMessageImpl resp = getResponse(); resp.init(hsc); return resp; }
java
private void validateInput(AuthenticationService authenticationService, String username) throws AuthenticationException { if (authenticationService == null) { throw new AuthenticationException("authenticationService cannot be null."); } else if (username == null) { throw new Auth...
python
def white(num_points=1024, b0=1.0, fs=1.0): """ generate time series with white noise that has constant PSD = b0, up to the nyquist frequency fs/2 N = number of samples b0 = desired power-spectral density in [X^2/Hz] where X is the unit of x fs = sampling frequency, i.e. 1/fs is the ...
java
public static Object exec(Method method, String[] paramNames, Map<String,?> params, Object instance) throws Throwable { Object[] paramValues = new Object[paramNames.length]; for(int c=0; c < paramNames.length; ++c) { paramValues[c] = params.get(paramNames[c]); } try { return metho...
java
public ServiceFuture<Void> purgeDeletedAsync(String vaultName, String location, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(purgeDeletedWithServiceResponseAsync(vaultName, location), serviceCallback); }
python
def parse_dunder_all(self): """Parse the __all__ definition in a module.""" assert self.current.value == '__all__' self.consume(tk.NAME) # More than one __all__ definition means we ignore all __all__. if self.dunder_all is not None or self.dunder_all_error is not None: ...
python
def _lincomb(self, a, x1, b, x2, out): """Implement the linear combination of ``x1`` and ``x2``. Compute ``out = a*x1 + b*x2`` using optimized BLAS routines if possible. This function is part of the subclassing API. Do not call it directly. Parameters ---------...
python
def parse_rec(filename): """ Parse a PASCAL VOC xml file """ tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_struct = {} obj_struct['name'] = obj.find('name').text obj_struct['pose'] = obj.find('pose').text obj_struct['truncated'] = int(obj.f...
python
def create_albaran_automatic(pk, list_lines): """ creamos de forma automatica el albaran """ line_bd = SalesLineAlbaran.objects.filter(line_order__pk__in=list_lines).values_list('line_order__pk') if line_bd.count() == 0 or len(list_lines) != len(line_bd[0]): # solo aq...
java
static boolean find( Map<List<TemporalExtendedPropositionDefinition>, Relation> epdToRelation, List<List<TemporalExtendedPropositionDefinition>> epdPairs, Map<TemporalExtendedPropositionDefinition, TemporalProposition> potentialInstance) { /* * Loop through the abst...
python
def parse_connection_setup(self): """Internal function used to parse connection setup response. """ # Only the ConnectionSetupRequest has been sent so far r = self.sent_requests[0] while 1: # print 'data_send:', repr(self.data_send) # print 'data_recv:',...
python
def newDocNodeEatName(self, doc, name, content): """Creation of a new node element within a document. @ns and @content are optional (None). NOTE: @content is supposed to be a piece of XML CDATA, so it allow entities references, but XML special chars need to be escaped first by usin...
java
private StringTreeNode getOrgHierarchyTree() { // Hierarchical data in a flat format. // If an Object array contains 1 String element, it is a leaf node. // Else an Object array contains 1 String element + object arrays and is a branch node. Object[] data = new Object[]{ "Australia", new Object[]{"ACT"}, ...
python
def zcount(self, name, min, max): """ Returns the number of elements in the sorted set at key ``name`` with a score between ``min`` and ``max``. """ return self.execute_command('ZCOUNT', name, min, max)
java
public void put(InputStream in, long length, String localFile, String remoteFile, FileTransferProgress progress) throws SshException, ChannelOpenException { ScpEngineIO scp = new ScpEngineIO("scp -t " /* + (verbose ? "-v " : "") */ + remoteFile, ssh.openSessionChannel()); try { scp.waitForResponse();...
java
public static PlotCanvas plot(double[][][] data) { double[] lowerBound = {data[0][0][0], data[0][0][1], data[0][0][2]}; double[] upperBound = {data[0][0][0], data[0][0][1], data[0][0][2]}; for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { ...
python
def numRegisteredForRoleName(event, roleName): ''' This tag allows one to access the number of registrations for any dance role using only the role's name. ''' if not isinstance(event, Event): return None try: role = DanceRole.objects.get(name=roleName) except Obje...
java
private Expression orOp(Data data) throws TemplateException { Expression expr = andOp(data); while (data.srcCode.forwardIfCurrent("||") || data.srcCode.forwardIfCurrentAndNoWordAfter("or")) { comments(data); expr = data.factory.opBool(expr, andOp(data), Factory.OP_BOOL_OR); } return expr; }
python
def R(self, value): """ measurement uncertainty""" self._R = value self._R1_2 = cholesky(self._R, lower=True)
python
def pre_save_title(instance, **kwargs): ''' Update article.languages ''' if instance.article.languages: languages = instance.article.languages.split(',') else: languages = [] if instance.language not in languages: languages.append(instance.language) instance.article.l...
java
private void tryEliminateOptionalArgs(ArrayList<Node> refs) { // Count the maximum number of arguments passed into this function all // all points of the program. int maxArgs = -1; for (Node n : refs) { if (ReferenceMap.isCallOrNewTarget(n)) { int numArgs = 0; Node firstArg = Refe...
python
def reverse(self): """ Reverse the robot's current motor directions. If the robot is currently running full speed forward, it will run full speed backward. If the robot is turning left at half-speed, it will turn right at half-speed. If the robot is currently stopped it will rema...
python
def register_segment_dcnm(self, cfg, seg_id_min, seg_id_max): """Register segmentation id pool with DCNM. """ orch_id = cfg.dcnm.orchestrator_id try: segid_range = self.dcnm_client.get_segmentid_range(orch_id) if segid_range is None: self.dcnm_client.set_...
python
def sync(self, policy, mediaSettings, client=None, clientId=None, title=None, sort=None, libtype=None, **kwargs): """ Add current library section as sync item for specified device. See description of :func:`~plexapi.library.LibrarySection.search()` for details about filtering / sorting ...
java
protected void loadArguments(List<Expression> argumentList, Parameter[] para) { if (para.length==0) return; ClassNode lastParaType = para[para.length - 1].getOriginType(); AsmClassGenerator acg = controller.getAcg(); OperandStack operandStack = controller.getOperandStack(); if (l...
java
public static Object getSerializedObjectFromString(Object asyncService, String serializedData) throws SerializationException { SerializationStreamFactory ssf = (SerializationStreamFactory)asyncService; return ssf.createStreamReader(serializedData).readObject(); }
python
def _psi2computations(dL_dpsi2, variance, Z, mu, S, gamma): """ Z - MxQ mu - NxQ S - NxQ gamma - NxQ """ # here are the "statistics" for psi1 and psi2 # Produced intermediate results: # _psi2_dvariance Q # _psi2_dZ MxQ # _psi2_dgamma NxQ # _psi2_d...
python
def rlmf_dqn_tiny(): """Tiny DQN params.""" hparams = rlmf_original() hparams = hparams.override_from_dict(rlmf_tiny_overrides()) hparams.batch_size = 1 hparams.base_algo = "dqn" hparams.base_algo_params = "dqn_original_params" hparams.add_hparam("dqn_num_frames", 128) hparams.add_hparam("dqn_save_every...
python
def ExcludedVolumeChain(q, Rg, nu): """Scattering intensity of a generalized excluded-volume Gaussian chain Inputs: ------- ``q``: independent variable ``Rg``: radius of gyration ``nu``: excluded volume exponent Formula: -------- ``(u^(1/nu)*gamma(0.5/nu)*gammainc_l...
python
def list_arc (archive, compression, cmd, verbosity, interactive): """List a ARC archive.""" cmdlist = [cmd] if verbosity > 1: cmdlist.append('v') else: cmdlist.append('l') cmdlist.append(archive) return cmdlist
python
def _pack_with_tf_ops(dataset, keys, length): """Helper-function for packing a dataset which has already been batched. See pack_dataset() Uses tf.while_loop. Slow. Args: dataset: a dataset containing padded batches of examples. keys: a list of strings length: an integer Returns: a dataset...
python
def spop(self, name, count=None): "Remove and return a random member of set ``name``" args = (count is not None) and [count] or [] return self.execute_command('SPOP', name, *args)
java
public static ZoneId toZoneId(TimeZone timeZone) { return ZoneId.of(timeZone.getID(), ZoneId.SHORT_IDS); }
python
def pmon(month): """ P the month >>> print(pmon('2012-08')) August, 2012 """ year, month = month.split('-') return '{month_name}, {year}'.format( month_name=calendar.month_name[int(month)], year=year, )
java
public void marshall(InspectorServiceAttributes inspectorServiceAttributes, ProtocolMarshaller protocolMarshaller) { if (inspectorServiceAttributes == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(i...
python
def get_epochs(self, time=None, stage=None, qual=None, chan=None, name=None): """Get list of events in the file. Parameters ---------- time : tuple of two float, optional start and end time of the period of interest stage : tuple of str, optional ...
java
@Override public Double sqrt2(Double arg1) { if (arg1 == null) { return Double.NaN; } else { return Math.sqrt(arg1); } }
java
public String getXmlEditorIncludes() throws JspException { StringBuffer result = new StringBuffer(1024); // first include general JQuery JS and UI components result.append("<script type=\"text/javascript\" src=\""); result.append(CmsWorkplace.getSkinUri()).append("jquery/packed/jquery....
java
public <T> void register(Class<T> event, EventObserver<T> observer){ if(event == null){ throw new IllegalArgumentException("Null Event type passed to register"); } if(observer == null){ throw new IllegalArgumentException("Null observer passed to register"); } ...
python
def p_conditional_expr(self, p): """ conditional_expr \ : logical_or_expr | logical_or_expr CONDOP assignment_expr COLON assignment_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.Conditional( predicate=p[1], c...
python
def _requests(self, url, method='GET', headers=None, params=None, data=None, errors=None): ''' a helper method for relaying requests from client to api ''' title = '%s._requests' % self.__class__.__name__ # import dependencies from time import time import requests # valid...
java
@Deprecated public CqlRecordWriter getRecordWriter(org.apache.hadoop.fs.FileSystem filesystem, org.apache.hadoop.mapred.JobConf job, String name, org.apache.hadoop.util.Progressable progress) throws IOException { return new CqlRecordWriter(job, progress); }
java
public boolean isParentAnEmptyDirectory(File file) { File parent = file.getParentFile(); if (parent != null && parent.exists() && parent.isDirectory() && parent.list().length == 0) { return true; } return false; }
java
protected IScope createStaticFeaturesScope(EObject featureCall, IScope parent, IFeatureScopeSession session) { return new StaticImportsScope(parent, session, asAbstractFeatureCall(featureCall)); }
java
@Deprecated public static Timestamp createFromUtcFields(Precision p, int zyear, int zmonth, int zday, int zhour, int zminute, int zsecond, BigDecimal frac, Integer offset) { return new Timestamp(p, zyear, zmonth, zday, zhou...
python
def submit_job(manager, job_config): """ Launch new job from specified config. May have been previously 'setup' if 'setup_params' in job_config is empty. """ # job_config is raw dictionary from JSON (from MQ or HTTP endpoint). job_id = job_config.get('job_id') try: command_line = job_con...
java
public static <T> Iterator<T> getSortedIterator (Iterator<T> itr, Comparator<T> comparator) { SortableArrayList<T> list = new SortableArrayList<T>(); CollectionUtil.addAll(list, itr); list.sort(comparator); return getUnmodifiableIterator(list); }
java
@Override public Statement apply(final Statement base, final Description description) { if (description.isSuite()) { return super.apply(classStatement(base), description); } return super.apply(statement(base), description); }
python
def keystroke_model(): """Generates a 2-state model with lognormal emissions and frequency smoothing""" model = Pohmm(n_hidden_states=2, init_spread=2, emissions=['lognormal', 'lognormal'], smoothing='freq', init_method='obs', ...
java
@NotNull @ObjectiveCName("makeAdminCommandWithGid:withUid:") public Command<Void> makeAdmin(final int gid, final int uid) { return callback -> modules.getGroupsModule().makeAdmin(gid, uid) .then(v -> callback.onResult(v)) .failure(e -> callback.onError(e)); }
python
def get_raw_data(self, mac, response_format='json'): """Get data from API as string. Keyword arguments: mac -- MAC address or OUI for searching response_format -- supported types you can see on the https://macaddress.io """ data = { self._FORMAT_...
java
private void _buildParameter( final Object value, final StringBuilder stmt, final List<Object> params ) { params.add( value ); stmt.append( _PARAM_SIGN_ ).append( params.size() ); }
java
@Override public final void setReliability(Reliability value) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setReliability", value); if (value != null) { /* Call the superclass's method to get the int value of the Reliability instan...
python
def __get_query_agg_ts(cls, field, time_field, interval=None, time_zone=None, start=None, end=None, agg_type='count', offset=None): """ Create an es_dsl aggregation object for getting the time series values for a field. :param field: field t...
java
private void startNewAlarm(LinkedListEntry entry) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "startNewAlarm", new Object[] { entry }); //start a new alarm entry.alarm = am.create(delta, percentLate, this, entry); if (TraceComponent.isAnyTracingEnable...
python
def values_to_labels(fg_vals, bg_vals): """ Convert two arrays of values to an array of labels and an array of scores. Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. Returns ...
python
def get_cod_ids(self, formula): """ Queries the COD for all cod ids associated with a formula. Requires mysql executable to be in the path. Args: formula (str): Formula. Returns: List of cod ids. """ # TODO: Remove dependency on external ...
python
def read(self, size): """Read raw bytes from the instrument. :param size: amount of bytes to be sent to the instrument :type size: integer :return: received bytes :return type: bytes """ raw_read = super(USBRawDevice, self).read received = bytearray() ...
java
public Observable<List<EntityRole>> getPrebuiltEntityRolesAsync(UUID appId, String versionId, UUID entityId) { return getPrebuiltEntityRolesWithServiceResponseAsync(appId, versionId, entityId).map(new Func1<ServiceResponse<List<EntityRole>>, List<EntityRole>>() { @Override public List<En...
python
def fast_relpath_optional(path, start): """A prefix-based relpath, with no normalization or support for returning `..`. Returns None if `start` is not a directory-aware prefix of `path`. """ if len(start) == 0: # Empty prefix. return path # Determine where the matchable prefix ends. pref_end = len...
python
def gc(self): """ Garbage collect overflow and/or aged entries. """ manifest = [] overlimit = len(self.data) - self.maxsize \ if self.maxsize is not None else 0 now = self.ttl is not None and self.timer() for key, entry in self.data.items(): if overlimit >...
python
def users(self, query, page=1, per_page=10): """ Get a single page of user results for a query. :param query [string]: Search terms. :param page [integer]: Page number to retrieve. (Optional; default: 1) :param per_page [integer]: Number of items per page. (Optional; default: 10...
java
private static void collectFields(Class<?> type, List<Field> fields) { final Field[] declaredFields = type.getDeclaredFields(); for (Field declaredField : declaredFields) { if (isPersistable(declaredField)) { fields.add(declaredField); } } if (type...
java
public List<LocationOccurrence> extractLocationNames(String text) { if (text == null) throw new IllegalArgumentException("text input to extractLocationNames should not be null"); // extract entities as <Entity Type, Start Index, Stop Index> return convertNERtoCLAVIN(namedEntityRecog...
python
def JSONList(*args, **kwargs): """Stores a list as JSON on database, with mutability support. If kwargs has a param `unique_sorted` (which evaluated to True), list values are made unique and sorted. """ type_ = JSON try: if kwargs.pop("unique_sorted"): type_ = JSONUniqueList...
java
public static SQLDatabase openSQLDatabase(File dbFile, KeyProvider provider) throws IOException, SQLException { Misc.checkNotNull(dbFile, "dbFile"); File dbDirectory = dbFile.getParentFile(); if (!dbDirectory.mkdirs()){ logger.info(String.format(Locale.ENGLISH, "Did not create direct...
python
def merge_channels(image_list): """ Merge channels of multiple scalar ANTsImage types into one multi-channel ANTsImage ANTsR function: `mergeChannels` Arguments --------- image_list : list/tuple of ANTsImage types scalar images to merge Returns ------- ANTsIma...
java
protected TryableSemaphore getFallbackSemaphore() { if (fallbackSemaphoreOverride == null) { TryableSemaphore _s = fallbackSemaphorePerCircuit.get(commandKey.name()); if (_s == null) { // we didn't find one cache so setup fallbackSemaphorePerCircuit.putIfA...
python
def cudnnSetConvolution2dDescriptor(convDesc, pad_h, pad_w, u, v, dilation_h, dilation_w, mode, computeType): """" Initialize a convolution descriptor. This function initializes a previously created convolution descriptor object into a 2D correlation. This function a...
java
public static String getStaticResourceVersion() { if (null == staticResourceVersion) { staticResourceVersion = getLatkeProperty("staticResourceVersion"); if (null == staticResourceVersion) { staticResourceVersion = String.valueOf(startupTimeMillis); } ...
java
@Override public CheckDNSAvailabilityResult checkDNSAvailability(CheckDNSAvailabilityRequest request) { request = beforeClientExecution(request); return executeCheckDNSAvailability(request); }
java
public static String denormalize(final CharSequence self) { final String s = self.toString(); // Don't do this in static initializer because we may never be needed. // TODO: Put this lineSeparator property somewhere everyone can use it. if (lineSeparator == null) { final Stri...
python
def add(workflow_definition: dict, templates_root: str): """Add a workflow definition to the Configuration Database. Templates are expected to be found in a directory tree with the following structure: - workflow_id: |- workflow_version |- stage_id |...
java
public<RET> RET same(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable) throws APIException, CadiException, LocatorException { RET ret = null; boolean retry = true; int retries = 0; Rcli<HttpURLConnection> client = retryable.lastClient(); try { do { // if no previous state, get the best ...
java
public void addWsByteBuffer(WsByteBuffer buffer) { if (this.allWsByteBuffers == null) { this.allWsByteBuffers = new Hashtable<WsByteBuffer, WsByteBuffer>(); } this.allWsByteBuffers.put(buffer, buffer); }
python
def create_push(self, push, repository_id, project=None): """CreatePush. Push changes to the repository. :param :class:`<GitPush> <azure.devops.v5_0.git.models.GitPush>` push: :param str repository_id: The name or ID of the repository. :param str project: Project ID or project na...
python
def custom_indicator_class_factory(indicator_type, base_class, class_dict, value_fields): """Internal method for dynamically building Custom Indicator Class.""" value_count = len(value_fields) def init_1(self, tcex, value1, xid, **kwargs): # pylint: disable=W0641 """Init method for Custom Indicato...
python
def to_original(self, x, y): """ Convert the input (x, y) positions from the rectified image to the original (unrectified) image. Parameters ---------- x, y: float or array-like of float The zero-index pixel coordinates in the rectified image. Retur...
java
private String parseQuotedToken(final char[] terminators) { char ch; i1 = pos; i2 = pos; boolean quoted = false; boolean charEscaped = false; while (hasChar()) { ch = chars[pos]; if (!quoted && isOneOf(ch, terminators)) { break; } if (!charEscaped && ch == '"') { quoted = !quoted; } ...
python
def _predict_with_probabilities(self, input_dataset, batch_size=None, verbose=True): """ Predict with probabilities. The core prediction part that both `evaluate` and `predict` share. Returns an SFrame with two columns, self.target, and "probabilities". The column wit...
java
private void loadImplementationsInJar(final Test test, final String parent, final String path, final JarInputStream stream) { try { JarEntry entry; while ((entry = stream.getNextJarEntry()) != null) { final String name = entry.g...
java
public ServiceFuture<Void> validateMoveResourcesAsync(String sourceResourceGroupName, ResourcesMoveInfo parameters, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(validateMoveResourcesWithServiceResponseAsync(sourceResourceGroupName, parameters), serviceCallback); }
java
@BetaApi( "The surface for long-running operations is not stable yet and may change in the future.") public final OperationFuture<Table, CreateTableFromSnapshotMetadata> createTableFromSnapshotAsync( CreateTableFromSnapshotRequest request) { return createTableFromSnapshotOperationCallable().futureCall...
java
public ArrayDeque<int[]> computeEditMapping() { // initialize tree and forest distance arrays double[][] treedist = new double[size1 + 1][size2 + 1]; double[][] forestdist = new double[size1 + 1][size2 + 1]; boolean rootNodePair = true; // treedist was already computed - the result is in delta and deltaB...
python
def path_to_url(path): """ Convert a path to a file: URL. The path will be made absolute and have quoted path parts. """ path = os.path.normpath(os.path.abspath(path)) url = urlparse.urljoin("file:", urllib2.pathname2url(path)) return url
python
def analyze(self, mode=None, timesteps=None): """Analyzes the grid by power flow analysis Analyze the grid for violations of hosting capacity. Means, perform a power flow analysis and obtain voltages at nodes (load, generator, stations/transformers and branch tees) and active/reactive p...