language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_port_profile_status_input_request_type_getnext_request_last_received_port_profile_info_profile_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_port_profile_status = ET.Element("get_port_profile_status") config = get_port_profile_status input = ET.SubElement(get_port_profile_status, "input") request_type = ET.SubElement(input, "request-type") getnext_request = ET.SubElement(request_type, "getnext-request") last_received_port_profile_info = ET.SubElement(getnext_request, "last-received-port-profile-info") profile_name = ET.SubElement(last_received_port_profile_info, "profile-name") profile_name.text = kwargs.pop('profile_name') callback = kwargs.pop('callback', self._callback) return callback(config)
java
@BetaApi public final AggregatedListAcceleratorTypesPagedResponse aggregatedListAcceleratorTypes( ProjectName project) { AggregatedListAcceleratorTypesHttpRequest request = AggregatedListAcceleratorTypesHttpRequest.newBuilder() .setProject(project == null ? null : project.toString()) .build(); return aggregatedListAcceleratorTypes(request); }
python
def sample_upper_hull(upper_hull, random_stream): """ Return a single value randomly sampled from the given `upper_hull`. Parameters ---------- upper_hull : List[pyars.hull.HullNode] Upper hull to evaluate. random_stream : numpy.random.RandomState (Seeded) stream of random values to use during sampling. Returns ---------- sample : float Single value randomly sampled from `upper_hull`. """ cdf = cumsum([node.pr for node in upper_hull]) # randomly choose a line segment U = random_stream.rand() node = next( (node for node, cdf_value in zip(upper_hull, cdf) if U < cdf_value), upper_hull[-1] # default is last line segment ) # sample along that line segment U = random_stream.rand() m, left, right = node.m, node.left, node.right M = max(m * right, m * left) x = (log(U * (exp(m * right - M) - exp(m * left - M)) + exp(m * left - M)) + M) / m assert(x >= left and x <= right) if isinf(x) or isnan(x): raise ValueError("sampled an infinite or 'nan' x") return x
java
public static int search(short[] shortArray, short value, int occurrence) { if(occurrence <= 0 || occurrence > shortArray.length) { throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than " + "the array length: " + occurrence); } int valuesSeen = 0; for(int i = 0; i < shortArray.length; i++) { if(shortArray[i] == value) { valuesSeen++; if(valuesSeen == occurrence) { return i; } } } return -1; }
java
protected FaihyUnifiedFailureResult newUnifiedFailureResult(FaihyUnifiedFailureType failureType, List<FaihyFailureErrorPart> errors) { return new FaihyUnifiedFailureResult(failureType, errors); }
java
public Set<Permission> authorize(AuthenticatedUser user, IResource resource) { if (user.isSuper()) return Permission.ALL; UntypedResultSet result; try { ResultMessage.Rows rows = authorizeStatement.execute(QueryState.forInternalCalls(), QueryOptions.forInternalCalls(ConsistencyLevel.LOCAL_ONE, Lists.newArrayList(ByteBufferUtil.bytes(user.getName()), ByteBufferUtil.bytes(resource.getName())))); result = UntypedResultSet.create(rows.result); } catch (RequestValidationException e) { throw new AssertionError(e); // not supposed to happen } catch (RequestExecutionException e) { logger.warn("CassandraAuthorizer failed to authorize {} for {}", user, resource); return Permission.NONE; } if (result.isEmpty() || !result.one().has(PERMISSIONS)) return Permission.NONE; Set<Permission> permissions = EnumSet.noneOf(Permission.class); for (String perm : result.one().getSet(PERMISSIONS, UTF8Type.instance)) permissions.add(Permission.valueOf(perm)); return permissions; }
java
private boolean accepted(Row row, List<IndexExpression> expressions) { if (!expressions.isEmpty()) { Columns columns = rowMapper.columns(row); for (IndexExpression expression : expressions) { if (!accepted(columns, expression)) { return false; } } } return true; }
python
def bool_from(obj, default=False): """Returns True if obj is not None and its string representation is not 0 or False (case-insensitive). If obj is None, 'default' is used. """ return str(obj).lower() not in ('0', 'false') if obj is not None else bool(default)
java
public Observable<ServiceResponse<Page<SiteInner>>> beginResumeNextWithServiceResponseAsync(final String nextPageLink) { return beginResumeNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<SiteInner>>, Observable<ServiceResponse<Page<SiteInner>>>>() { @Override public Observable<ServiceResponse<Page<SiteInner>>> call(ServiceResponse<Page<SiteInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(beginResumeNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public StringBuffer format(Object pObj, StringBuffer pToAppendTo, FieldPosition pPos) { if (!(pObj instanceof Time)) { throw new IllegalArgumentException("Must be instance of " + Time.class); } return pToAppendTo.append(format(pObj)); }
java
public JMenuItem add(UserInterfaceAction action) { try { Method _specializedMethod = getClass().getMethod(FUNCTION_NAME_ADD, new Class[] { action.getClass() }); return (JMenuItem) _specializedMethod.invoke(this, new Object[] { action }); } catch (Exception _exception) { _exception.printStackTrace(System.err); return null; } }
python
def clone(self, opts): ''' Create a new instance of this type with the specified options. Args: opts (dict): The type specific options for the new instance. ''' topt = self.opts.copy() topt.update(opts) return self.__class__(self.modl, self.name, self.info, topt)
python
def ravel(self, name=None): """ Convert 2D histogram into 1D histogram with the y-axis repeated along the x-axis, similar to NumPy's ravel(). """ nbinsx = self.nbins(0) nbinsy = self.nbins(1) left_edge = self.xedgesl(1) right_edge = self.xedgesh(nbinsx) out = Hist(nbinsx * nbinsy, left_edge, nbinsy * (right_edge - left_edge) + left_edge, type=self.TYPE, name=name, title=self.title, **self.decorators) for i, bin in enumerate(self.bins(overflow=False)): out.SetBinContent(i + 1, bin.value) out.SetBinError(i + 1, bin.error) return out
python
def localize(date_time, time_zone): """Returns a datetime adjusted to a timezone: * If dateTime is a naive datetime (datetime with no timezone information), timezone information is added but date and time remains the same. * If dateTime is not a naive datetime, a datetime object with new tzinfo attribute is returned, adjusting the date and time data so the result is the same UTC time. """ if datetime_is_naive(date_time): ret = time_zone.localize(date_time) else: ret = date_time.astimezone(time_zone) return ret
python
def variable_length_to_fixed_length_categorical( self, left_edge=4, right_edge=4, max_length=15): """ Encode variable-length sequences using a fixed-length encoding designed for preserving the anchor positions of class I peptides. The sequences must be of length at least left_edge + right_edge, and at most max_length. Parameters ---------- left_edge : int, size of fixed-position left side right_edge : int, size of the fixed-position right side max_length : sequence length of the resulting encoding Returns ------- numpy.array of integers with shape (num sequences, max_length) """ cache_key = ( "fixed_length_categorical", left_edge, right_edge, max_length) if cache_key not in self.encoding_cache: fixed_length_sequences = ( self.sequences_to_fixed_length_index_encoded_array( self.sequences, left_edge=left_edge, right_edge=right_edge, max_length=max_length)) self.encoding_cache[cache_key] = fixed_length_sequences return self.encoding_cache[cache_key]
python
def check(): """Command for checking upgrades.""" upgrader = InvenioUpgrader() logger = upgrader.get_logger() try: # Run upgrade pre-checks upgrades = upgrader.get_upgrades() # Check if there's anything to upgrade if not upgrades: logger.info("All upgrades have been applied.") return logger.info("Following upgrade(s) have not been applied yet:") for u in upgrades: logger.info( " * {0} {1}".format(u.name, u.info)) logger.info("Running pre-upgrade checks...") upgrader.pre_upgrade_checks(upgrades) logger.info("Upgrade check successful - estimated time for upgrading" " Invenio is %s..." % upgrader.human_estimate(upgrades)) except RuntimeError as e: for msg in e.args: logger.error(unicode(msg)) logger.error("Upgrade check failed. Aborting.") raise
python
def flux_randomization(model, threshold, tfba, solver): """Find a random flux solution on the boundary of the solution space. The reactions in the threshold dictionary are constrained with the associated lower bound. Args: model: MetabolicModel to solve. threshold: dict of additional lower bounds on reaction fluxes. tfba: If True enable thermodynamic constraints. solver: LP solver instance to use. Returns: An iterator of reaction ID and reaction flux pairs. """ optimize = {} for reaction_id in model.reactions: if model.is_reversible(reaction_id): optimize[reaction_id] = 2*random.random() - 1.0 else: optimize[reaction_id] = random.random() fba = _get_fba_problem(model, tfba, solver) for reaction_id, value in iteritems(threshold): fba.prob.add_linear_constraints(fba.get_flux_var(reaction_id) >= value) fba.maximize(optimize) for reaction_id in model.reactions: yield reaction_id, fba.get_flux(reaction_id)
java
public CMAArray<CMASpaceMembership> fetchAll(Map<String, String> query) { throwIfEnvironmentIdIsSet(); return fetchAll(spaceId, query); }
java
synchronized public void addClusterChangeListener(ClusterEventListener l) { if (listeners == null) listeners = new Vector(); listeners.addElement(l); }
python
def request_anime(client, aid: int) -> 'Anime': """Make an anime API request.""" response = api.httpapi_request(client, request='anime', aid=aid) etree = api.unpack_xml(response.text) return _unpack_anime(etree.getroot())
java
public static RequestReporter initRequestReporter(FilterConfig filterConfig) { String className = filterConfig.getInitParameter(SimonServletFilter.INIT_PARAM_REQUEST_REPORTER_CLASS); if (className == null) { return new DefaultRequestReporter(); } else { try { return (RequestReporter) Class.forName(className).newInstance(); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException classNotFoundException) { throw new IllegalArgumentException("Invalid Request reporter class name", classNotFoundException); } } }
java
public void marshall(InstanceFleet instanceFleet, ProtocolMarshaller protocolMarshaller) { if (instanceFleet == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(instanceFleet.getId(), ID_BINDING); protocolMarshaller.marshall(instanceFleet.getName(), NAME_BINDING); protocolMarshaller.marshall(instanceFleet.getStatus(), STATUS_BINDING); protocolMarshaller.marshall(instanceFleet.getInstanceFleetType(), INSTANCEFLEETTYPE_BINDING); protocolMarshaller.marshall(instanceFleet.getTargetOnDemandCapacity(), TARGETONDEMANDCAPACITY_BINDING); protocolMarshaller.marshall(instanceFleet.getTargetSpotCapacity(), TARGETSPOTCAPACITY_BINDING); protocolMarshaller.marshall(instanceFleet.getProvisionedOnDemandCapacity(), PROVISIONEDONDEMANDCAPACITY_BINDING); protocolMarshaller.marshall(instanceFleet.getProvisionedSpotCapacity(), PROVISIONEDSPOTCAPACITY_BINDING); protocolMarshaller.marshall(instanceFleet.getInstanceTypeSpecifications(), INSTANCETYPESPECIFICATIONS_BINDING); protocolMarshaller.marshall(instanceFleet.getLaunchSpecifications(), LAUNCHSPECIFICATIONS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
protected Comparator<OpenCLDevice> getDefaultAcceleratorComparator() { return new Comparator<OpenCLDevice>() { @Override public int compare(OpenCLDevice left, OpenCLDevice right) { return (right.getMaxComputeUnits() - left.getMaxComputeUnits()); } }; }
python
def make_secure_adaptor(service, mod, client_id, client_secret, tok_update_sec=None): """ :param service: Service to wrap in. :param mod: Name (type) of token refresh backend. :param client_id: Client identifier. :param client_secret: Client secret. :param tok_update_sec: Token update interval in seconds. """ if mod == 'TVM': return SecureServiceAdaptor(service, TVM(client_id, client_secret), tok_update_sec) return SecureServiceAdaptor(service, Promiscuous(), tok_update_sec)
python
def get_position(self, dt): """Given dt in [0, 1], return the current position of the tile.""" return self.sx + self.dx * dt, self.sy + self.dy * dt
java
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case XbasePackage.XBASIC_FOR_LOOP_EXPRESSION__EXPRESSION: return basicSetExpression(null, msgs); case XbasePackage.XBASIC_FOR_LOOP_EXPRESSION__EACH_EXPRESSION: return basicSetEachExpression(null, msgs); case XbasePackage.XBASIC_FOR_LOOP_EXPRESSION__INIT_EXPRESSIONS: return ((InternalEList<?>)getInitExpressions()).basicRemove(otherEnd, msgs); case XbasePackage.XBASIC_FOR_LOOP_EXPRESSION__UPDATE_EXPRESSIONS: return ((InternalEList<?>)getUpdateExpressions()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); }
python
def explain_instance(self, text_instance, classifier_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='cosine', model_regressor=None): """Generates explanations for a prediction. First, we generate neighborhood data by randomly hiding features from the instance (see __data_labels_distance_mapping). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_base.py). Args: text_instance: raw text string to be explained. classifier_fn: classifier prediction probability function, which takes a list of d strings and outputs a (d, k) numpy array with prediction probabilities, where k is the number of classes. For ScikitClassifiers , this is classifier.predict_proba. labels: iterable with labels to be explained. top_labels: if not None, ignore labels and produce explanations for the K labels with highest prediction probabilities, where K is this parameter. num_features: maximum number of features present in explanation num_samples: size of the neighborhood to learn the linear model distance_metric: the distance metric to use for sample weighting, defaults to cosine similarity model_regressor: sklearn regressor to use in explanation. Defaults to Ridge regression in LimeBase. Must have model_regressor.coef_ and 'sample_weight' as a parameter to model_regressor.fit() Returns: An Explanation object (see explanation.py) with the corresponding explanations. """ indexed_string = IndexedCharacters( text_instance, bow=self.bow) if self.char_level else IndexedString( text_instance, bow=self.bow, split_expression=self.split_expression) domain_mapper = TextDomainMapper(indexed_string) data, yss, distances = self.__data_labels_distances( indexed_string, classifier_fn, num_samples, distance_metric=distance_metric) if self.class_names is None: self.class_names = [str(x) for x in range(yss[0].shape[0])] ret_exp = explanation.Explanation(domain_mapper=domain_mapper, class_names=self.class_names, random_state=self.random_state) ret_exp.predict_proba = yss[0] if top_labels: labels = np.argsort(yss[0])[-top_labels:] ret_exp.top_labels = list(labels) ret_exp.top_labels.reverse() for label in labels: (ret_exp.intercept[label], ret_exp.local_exp[label], ret_exp.score, ret_exp.local_pred) = self.base.explain_instance_with_data( data, yss, distances, label, num_features, model_regressor=model_regressor, feature_selection=self.feature_selection) return ret_exp
java
public Model addEdge(Edge edge) { edges.add(edge); if (isNotNull(edge.getSourceVertex()) && !vertices.contains(edge.getSourceVertex())) { vertices.add(edge.getSourceVertex()); } if (isNotNull(edge.getTargetVertex()) && !vertices.contains(edge.getTargetVertex())) { vertices.add(edge.getTargetVertex()); } return this; }
java
protected ModelAndView buildCallbackViewViaRedirectUri(final J2EContext context, final String clientId, final Authentication authentication, final OAuthCode code) { val attributes = authentication.getAttributes(); val state = attributes.get(OAuth20Constants.STATE).get(0).toString(); val nonce = attributes.get(OAuth20Constants.NONCE).get(0).toString(); val redirectUri = context.getRequestParameter(OAuth20Constants.REDIRECT_URI); LOGGER.debug("Authorize request verification successful for client [{}] with redirect uri [{}]", clientId, redirectUri); var callbackUrl = redirectUri; callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.CODE, code.getId()); if (StringUtils.isNotBlank(state)) { callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.STATE, state); } if (StringUtils.isNotBlank(nonce)) { callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.NONCE, nonce); } LOGGER.debug("Redirecting to URL [{}]", callbackUrl); val params = new LinkedHashMap<String, String>(); params.put(OAuth20Constants.CODE, code.getId()); params.put(OAuth20Constants.STATE, state); params.put(OAuth20Constants.NONCE, nonce); params.put(OAuth20Constants.CLIENT_ID, clientId); return buildResponseModelAndView(context, servicesManager, clientId, callbackUrl, params); }
python
def delete_account_group(self, account_id, group_id, **kwargs): # noqa: E501 """Delete a group. # noqa: E501 An endpoint for deleting a group. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/policy-groups/{groupID} -H 'Authorization: Bearer API_KEY'` # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.delete_account_group(account_id, group_id, asynchronous=True) >>> result = thread.get() :param asynchronous bool :param str account_id: Account ID. (required) :param str group_id: The ID of the group to be deleted. (required) :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('asynchronous'): return self.delete_account_group_with_http_info(account_id, group_id, **kwargs) # noqa: E501 else: (data) = self.delete_account_group_with_http_info(account_id, group_id, **kwargs) # noqa: E501 return data
python
def format_error(status=None, title=None, detail=None, code=None): '''Formatting JSON API Error Object Constructing an error object based on JSON API standard ref: http://jsonapi.org/format/#error-objects Args: status: Can be a http status codes title: A summary of error detail: A descriptive error message code: Application error codes (if any) Returns: A dictionary contains of status, title, detail and code ''' error = {} error.update({ 'title': title }) if status is not None: error.update({ 'status': status }) if detail is not None: error.update({ 'detail': detail }) if code is not None: error.update({ 'code': code }) return error
python
def update_ports(self): """ Sets the `ports` attribute to the set of valid port values set in the configuration. """ ports = set() for port in self.configured_ports: try: ports.add(int(port)) except ValueError: logger.error("Invalid port value: %s", port) continue self.ports = ports
java
public static BlockPos chunkPosition(BlockPos pos) { return new BlockPos(pos.getX() - (pos.getX() >> 4) * 16, pos.getY() - (pos.getY() >> 4) * 16, pos.getZ() - (pos.getZ() >> 4) * 16); }
python
def classifySPoutput(targetOutputColumns, outputColumns): """ Classify the SP output @param targetOutputColumns (list) The target outputs, corresponding to different classes @param outputColumns (array) The current output @return classLabel (int) classification outcome """ numTargets, numDims = targetOutputColumns.shape overlap = np.zeros((numTargets,)) for i in range(numTargets): overlap[i] = percentOverlap(outputColumns, targetOutputColumns[i, :]) classLabel = np.argmax(overlap) return classLabel
java
public LeafNode<K, V> prevNode() { if (leftid == NULL_ID) { return null; } return (LeafNode<K, V>) tree.getNode(leftid); }
java
public synchronized void insert(double value) { buffer[bufferCount] = value; bufferCount++; if (bufferCount == buffer.length) { insertBatch(); compress(); } }
java
protected int transitionWithRoot(int nodePos, char c) { int b = base[nodePos]; int p; p = b + c + 1; if (b != check[p]) { if (nodePos == 0) return 0; return -1; } return p; }
python
def neighbors2(self, distance, chain_residue, atom = None, resid_list = None): #atom = " CA " '''this one is more precise since it uses the chain identifier also''' if atom == None: # consider all atoms lines = [line for line in self.atomlines(resid_list) if line[17:20] in allowed_PDB_residues_types] else: # consider only given atoms lines = [line for line in self.atomlines(resid_list) if line[17:20] in allowed_PDB_residues_types and line[12:16] == atom] shash = spatialhash.SpatialHash(distance) for line in lines: pos = (float(line[30:38]), float(line[38:46]), float(line[46:54])) shash.insert(pos, line[21:26]) neighbor_list = [] for line in lines: resid = line[21:26] if resid == chain_residue: pos = (float(line[30:38]), float(line[38:46]), float(line[46:54])) for data in shash.nearby(pos, distance): if data[1] not in neighbor_list: neighbor_list.append(data[1]) neighbor_list.sort() return neighbor_list
java
public Map<String, Integer> countByStatusAndMainComponentUuids(DbSession dbSession, CeQueueDto.Status status, Set<String> projectUuids) { if (projectUuids.isEmpty()) { return emptyMap(); } ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder(); executeLargeUpdates( projectUuids, partitionOfProjectUuids -> { List<QueueCount> i = mapper(dbSession).countByStatusAndMainComponentUuids(status, partitionOfProjectUuids); i.forEach(o -> builder.put(o.getMainComponentUuid(), o.getTotal())); }); return builder.build(); }
python
def unpack(n, r=32): """Yield r > 0 bit-length integers splitting n into chunks. >>> list(unpack(42, 1)) [0, 1, 0, 1, 0, 1] >>> list(unpack(256, 8)) [0, 1] >>> list(unpack(2, 0)) Traceback (most recent call last): ... ValueError: unpack needs r > 0 """ if r < 1: raise ValueError('unpack needs r > 0') mask = (1 << r) - 1 while n: yield n & mask n >>= r
python
def convert_cluster_dict_keys_to_aliases(self, cluster_dict, alias_hash): ''' Parameters ---------- cluster_dict : dict dictionary stores information on pre-placement clustering alias_hash : dict Stores information on each input read file given to GraftM, the corresponding reads found within each file, and their taxonomy Returns -------- updated cluster_dict dict containing alias indexes for keys. ''' output_dict = {} directory_to_index_dict = {os.path.split(item["output_path"])[0] : key for key, item in alias_hash.iteritems()} for key, item in cluster_dict.iteritems(): cluster_file_directory = os.path.split(key)[0] cluster_idx = directory_to_index_dict[cluster_file_directory] output_dict[cluster_idx] = item return output_dict
java
public static String getString(String key) { if (RESOURCE_BUNDLE == null) throw new RuntimeException("Localized messages from resource bundle '" + BUNDLE_NAME + "' not loaded during initialization of driver."); try { if (key == null) throw new IllegalArgumentException("Message key can not be null"); String message = RESOURCE_BUNDLE.getString(key); if (message == null) message = "Missing error message for key '" + key + "'"; return message; } catch (MissingResourceException e) { return '!' + key + '!'; } }
java
@Override public void onModuleLoad() { Theme defaultTheme = ThemeController.get().getDefaultTheme(); defaultTheme.addLink(new CssLink("theme/default/style/bootstrap.min.css", -2)); defaultTheme.addLink(new CssLink("theme/default/style/pwt-core.css", 0)); IconFont font = new IconFont("theme/default/style/fontello.css", "icon-"); font.addAlias("add", "plus"); font.addAlias("save", "floppy"); font.addAlias("view", "search"); font.addAlias("drag", "menu"); defaultTheme.setIconFont(font); ThemeController.get().installDefaultTheme(); }
python
def unset_impact_state(self): """Unset impact, only if impact state change is set in configuration :return: None """ cls = self.__class__ if cls.enable_problem_impacts_states_change and not self.state_changed_since_impact: self.state = self.state_before_impact self.state_id = self.state_id_before_impact
java
public Map<String, String> mapAllStrings(String uri) throws IOException { Map<String, String> strings = new HashMap<>(); Map<String, URL> resourcesMap = getResourcesMap(uri); for (Iterator iterator = resourcesMap.entrySet().iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); String name = (String) entry.getKey(); URL url = (URL) entry.getValue(); String value = readContents(url); strings.put(name, value); } return strings; }
python
def clientConnected(self, proto): """ Called when a client connects to the bus. This method assigns the new connection a unique bus name. """ proto.uniqueName = ':1.%d' % (self.next_id,) self.next_id += 1 self.clients[proto.uniqueName] = proto
python
def gmean(x, weights=None): """ Return the weighted geometric mean of x """ w_arr, x_arr = _preprocess_inputs(x, weights) return np.exp((w_arr*np.log(x_arr)).sum(axis=0) / w_arr.sum(axis=0))
python
def from_element(cls, element): """Set the resource properties from a ``<res>`` element. Args: element (~xml.etree.ElementTree.Element): The ``<res>`` element """ def _int_helper(name): """Try to convert the name attribute to an int, or None.""" result = element.get(name) if result is not None: try: return int(result) except ValueError: raise DIDLMetadataError( 'Could not convert {0} to an integer'.format(name)) else: return None content = {} # required content['protocol_info'] = element.get('protocolInfo') if content['protocol_info'] is None: raise DIDLMetadataError('Could not create Resource from Element: ' 'protocolInfo not found (required).') # Optional content['import_uri'] = element.get('importUri') content['size'] = _int_helper('size') content['duration'] = element.get('duration') content['bitrate'] = _int_helper('bitrate') content['sample_frequency'] = _int_helper('sampleFrequency') content['bits_per_sample'] = _int_helper('bitsPerSample') content['nr_audio_channels'] = _int_helper('nrAudioChannels') content['resolution'] = element.get('resolution') content['color_depth'] = _int_helper('colorDepth') content['protection'] = element.get('protection') content['uri'] = element.text return cls(**content)
python
def fastqIteratorComplex(fn, useMutableString=False, verbose=False): """ A generator function which yields FastqSequence objects read from a file or stream. This iterator can handle fastq files that have their sequence and/or their quality data split across multiple lines (i.e. there are newline characters in the sequence and quality strings). :param fn: A file-like stream or a string; if this is a string, it's treated as a filename specifying the location of an input fastq file, else it's treated as a file-like object, which must have a readline() method. :param useMustableString: if True, construct sequences from lists of chars, rather than python string objects, to allow more efficient editing. Use with caution. :param verbose: if True, print messages on progress to stderr. :param debug: if True, print debugging messages to stderr. :param sanger: if True, assume quality scores are in sanger format. Otherwise, assume they're in Illumina format. """ fh = fn if type(fh).__name__ == "str": fh = open(fh) prevLine = None # try to get an idea of how much data we have... pind = None if verbose: try: totalLines = linesInFile(fh.name) pind = ProgressIndicator(totalToDo=totalLines, messagePrefix="completed", messageSuffix="of processing " + fh.name) except AttributeError: sys.stderr.write("fastqIterator -- warning: " + "unable to show progress for stream") verbose = False while True: # either we have a sequence header left over from the # prev call, or we need to read a new one from the file... # try to do that now name, prevLine = fastq_complex_parse_seq_header(fh, prevLine, pind, verbose) # read lines until we hit a qual header --> this is our sequence data seqdata, line = fastq_complex_parse_seq(fh, pind, verbose) # <line> is now a qual header, keep reading until we see # a sequence header.. or we run out of lines.. this is our quality data qualdata, line, prevLine = fastq_complex_parse_qual(fh, line, prevLine, verbose, pind) # package it all up.. yield NGSRead(seqdata, name, qualdata, useMutableString) if verbose: pind.showProgress() # remember where we stopped for next call, or finish prevLine = line if prevLine == "": break
python
def median_fltr(dem, fsize=7, origmask=False): """Scipy.ndimage median filter Does not properly handle NaN """ print("Applying median filter with size %s" % fsize) from scipy.ndimage.filters import median_filter dem_filt_med = median_filter(dem.filled(np.nan), fsize) #Now mask all nans out = np.ma.fix_invalid(dem_filt_med, copy=False, fill_value=dem.fill_value) if origmask: out = np.ma.array(out, mask=dem.mask, fill_value=dem.fill_value) out.set_fill_value(dem.fill_value) return out
java
private static StringMap filterParam(StringMap params) { final StringMap ret = new StringMap(); if (params == null) { return ret; } params.forEach(new StringMap.Consumer() { @Override public void accept(String key, Object value) { if (value == null) { return; } String val = value.toString(); if ((key.startsWith("x:") || key.startsWith("x-qn-meta-")) && !val.equals("")) { ret.put(key, val); } } }); return ret; }
java
public FirewallRuleInner createOrUpdateFirewallRule(String resourceGroupName, String accountName, String name, FirewallRuleInner parameters) { return createOrUpdateFirewallRuleWithServiceResponseAsync(resourceGroupName, accountName, name, parameters).toBlocking().single().body(); }
python
def __set_html(self, html=None): """ Sets the html content in the View using given body. :param html: Html content. :type html: unicode """ self.__html = self.__get_html(html) self.__view.setHtml(self.__html)
java
private static final double scoreAfp(AFP afp, double badRmsd, double fragScore) { //longer AFP with low rmsd is better double s, w; //s = (rmsdCut - afptmp.rmsd) * afptmp.len; //the same scroing strategy as that in the post-processing w = afp.getRmsd() / badRmsd; w = w * w; s = fragScore * (1.0 - w); return s; }
python
def search(self, CorpNum, JobID, Type, TaxType, PurposeType, TaxRegIDType, TaxRegIDYN, TaxRegID, Page, PerPage, Order, UserID=None): """ ์ˆ˜์ง‘ ๊ฒฐ๊ณผ ์กฐํšŒ args CorpNum : ํŒ๋นŒํšŒ์› ์‚ฌ์—…์ž๋ฒˆํ˜ธ JobID : ์ž‘์—…์•„์ด๋”” Type : ๋ฌธ์„œํ˜•ํƒœ ๋ฐฐ์—ด, N-์ผ๋ฐ˜์ „์ž์„ธ๊ธˆ๊ณ„์‚ฐ์„œ, M-์ˆ˜์ •์ „์ž์„ธ๊ธˆ๊ณ„์‚ฐ์„œ TaxType : ๊ณผ์„ธํ˜•ํƒœ ๋ฐฐ์—ด, T-๊ณผ์„ธ, N-๋ฉด์„ธ, Z-์˜์„ธ PurposeType : ์˜์ˆ˜/์ฒญ๊ตฌ, R-์˜์ˆ˜, C-์ฒญ๊ตฌ, N-์—†์Œ TaxRegIDType : ์ข…์‚ฌ์—…์žฅ๋ฒˆํ˜ธ ์‚ฌ์—…์ž์œ ํ˜•, S-๊ณต๊ธ‰์ž, B-๊ณต๊ธ‰๋ฐ›๋Š”์ž, T-์ˆ˜ํƒ์ž TaxRegIDYN : ์ข…์‚ฌ์—…์žฅ๋ฒˆํ˜ธ ์œ ๋ฌด, ๊ณต๋ฐฑ-์ „์ฒด์กฐํšŒ, 0-์ข…์‚ฌ์—…์žฅ๋ฒˆํ˜ธ ์—†์Œ, 1-์ข…์‚ฌ์—…์žฅ๋ฒˆํ˜ธ ์žˆ์Œ TaxRegID : ์ข…์‚ฌ์—…์žฅ๋ฒˆํ˜ธ, ์ฝค๋งˆ(",")๋กœ ๊ตฌ๋ถ„ ํ•˜์—ฌ ๊ตฌ์„ฑ ex) '0001,0002' Page : ํŽ˜์ด์ง€ ๋ฒˆํ˜ธ PerPage : ํŽ˜์ด์ง€๋‹น ๋ชฉ๋ก ๊ฐœ์ˆ˜, ์ตœ๋Œ€ 1000๊ฐœ Order : ์ •๋ ฌ ๋ฐฉํ–ฅ, D-๋‚ด๋ฆผ์ฐจ์ˆœ, A-์˜ค๋ฆ„์ฐจ์ˆœ UserID : ํŒ๋นŒํšŒ์› ์•„์ด๋”” return ์ˆ˜์ง‘ ๊ฒฐ๊ณผ ์ •๋ณด raise PopbillException """ if JobID == None or len(JobID) != 18: raise PopbillException(-99999999, "์ž‘์—…์•„์ด๋””(jobID)๊ฐ€ ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค.") uri = '/HomeTax/Taxinvoice/' + JobID uri += '?Type=' + ','.join(Type) uri += '&TaxType=' + ','.join(TaxType) uri += '&PurposeType=' + ','.join(PurposeType) uri += '&TaxRegIDType=' + TaxRegIDType uri += '&TaxRegID=' + TaxRegID uri += '&Page=' + str(Page) uri += '&PerPage=' + str(PerPage) uri += '&Order=' + Order if TaxRegIDYN != '': uri += '&TaxRegIDYN=' + TaxRegIDYN return self._httpget(uri, CorpNum, UserID)
java
protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) { return createPump(is, os, closeWhenExhausted, true); }
java
public void marshall(OrderByElement orderByElement, ProtocolMarshaller protocolMarshaller) { if (orderByElement == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(orderByElement.getFieldName(), FIELDNAME_BINDING); protocolMarshaller.marshall(orderByElement.getSortOrder(), SORTORDER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
python
def _copy(self, other, copy_func): """ Copies the contents of another Constructable object to itself :param object: Another instance of the same class :param copy_func: An reference of copy.copy() or copy.deepcopy() to use when copying lists, dicts and objects """ super(Constructable, self)._copy(other, copy_func) self.method = other.method self._indefinite = other._indefinite
python
def unpack(self, struct): """Read as many bytes as are required to extract struct then unpack and return a tuple of the values. Raises ------ UnderflowDecodeError Raised when a read failed to extract enough bytes from the underlying stream to extract the bytes. Parameters ---------- struct: struct.Struct Returns ------- tuple Tuple of extracted values. """ v = struct.unpack(self.read(struct.size)) return v
java
private boolean hasRoleMaster(String userId, String domain) { DomainRoleEntry domainRole = domainAccessStore.getDomainRole(userId, Role.MASTER); if (domainRole == null || !Arrays.asList(domainRole.getDomains()).contains(domain)) { return false; } return true; }
java
public <T extends BaseNode> T attachNode(BuildContext context, T candidate) { BaseNode node = null; RuleBasePartitionId partition = null; if ( candidate.getType() == NodeTypeEnums.EntryPointNode ) { // entry point nodes are always shared node = context.getKnowledgeBase().getRete().getEntryPointNode( ((EntryPointNode) candidate).getEntryPoint() ); // all EntryPointNodes belong to the main partition partition = RuleBasePartitionId.MAIN_PARTITION; } else if ( candidate.getType() == NodeTypeEnums.ObjectTypeNode ) { // object type nodes are always shared Map<ObjectType, ObjectTypeNode> map = context.getKnowledgeBase().getRete().getObjectTypeNodes( context.getCurrentEntryPoint() ); if ( map != null ) { ObjectTypeNode otn = map.get( ((ObjectTypeNode) candidate).getObjectType() ); if ( otn != null ) { // adjusting expiration offset otn.mergeExpirationOffset( (ObjectTypeNode) candidate ); node = otn; } } // all ObjectTypeNodes belong to the main partition partition = RuleBasePartitionId.MAIN_PARTITION; } else if ( isSharingEnabledForNode( context, candidate ) ) { if ( (context.getTupleSource() != null) && NodeTypeEnums.isLeftTupleSink( candidate ) ) { node = context.getTupleSource().getSinkPropagator().getMatchingNode( candidate ); } else if ( (context.getObjectSource() != null) && NodeTypeEnums.isObjectSink( candidate ) ) { node = context.getObjectSource().getObjectSinkPropagator().getMatchingNode( candidate ); } else { throw new RuntimeException( "This is a bug on node sharing verification. Please report to development team." ); } } if ( node != null && !areNodesCompatibleForSharing(context, node, candidate) ) { node = null; } if ( node == null ) { // only attach() if it is a new node node = candidate; // new node, so it must be labeled if ( partition == null ) { // if it does not has a predefined label if ( context.getPartitionId() == null ) { // if no label in current context, create one context.setPartitionId( context.getKnowledgeBase().createNewPartitionId() ); } partition = context.getPartitionId(); } // set node whit the actual partition label node.setPartitionId( context, partition ); node.attach(context); // adds the node to the context list to track all added nodes context.getNodes().add( node ); } else { // shared node found mergeNodes(node, candidate); // undo previous id assignment context.releaseId( candidate ); if ( partition == null && context.getPartitionId() == null ) { partition = node.getPartitionId(); // if no label in current context, create one context.setPartitionId( partition ); } } node.addAssociation( context, context.getRule() ); return (T)node; }
java
public static String mix(String string, int key) { return ascii(JavaEncrypt.base64(xor(string, key)), key); }
java
public static byte[] encodeSingleNullableDesc(byte[] value, int prefixPadding, int suffixPadding) { if (prefixPadding <= 0 && suffixPadding <= 0) { if (value == null) { return new byte[] {NULL_BYTE_LOW}; } int length = value.length; if (length == 0) { return new byte[] {NOT_NULL_BYTE_LOW}; } byte[] dst = new byte[1 + length]; dst[0] = NOT_NULL_BYTE_LOW; while (--length >= 0) { dst[1 + length] = (byte) (~value[length]); } return dst; } if (value == null) { byte[] dst = new byte[prefixPadding + 1 + suffixPadding]; dst[prefixPadding] = NULL_BYTE_LOW; return dst; } int length = value.length; byte[] dst = new byte[prefixPadding + 1 + length + suffixPadding]; dst[prefixPadding] = NOT_NULL_BYTE_LOW; while (--length >= 0) { dst[prefixPadding + 1 + length] = (byte) (~value[length]); } return dst; }
python
def _merge_states(self, states): """ Merges a list of states. :param states: the states to merge :returns SimState: the resulting state """ if self._hierarchy: optimal, common_history, others = self._hierarchy.most_mergeable(states) else: optimal, common_history, others = states, None, [] if len(optimal) >= 2: # We found optimal states (states that share a common ancestor) to merge. # Compute constraints for each state starting from the common ancestor, # and use them as merge conditions. constraints = [s.history.constraints_since(common_history) for s in optimal] o = optimal[0] m, _, _ = o.merge(*optimal[1:], merge_conditions=constraints, common_ancestor=common_history.strongref_state ) else: l.warning( "Cannot find states with common history line to merge. Fall back to the naive merging strategy " "and merge all states." ) s = states[0] m, _, _ = s.merge(*states[1:]) others = [] if self._hierarchy: self._hierarchy.add_state(m) if len(others): others.append(m) return self._merge_states(others) else: return m
java
public static void writeToOutputStream(String s, OutputStream output, String encoding) throws IOException { BufferedReader reader = new BufferedReader(new StringReader(s)); PrintStream writer; if (encoding != null) { writer = new PrintStream(output, true, encoding); } else { writer = new PrintStream(output, true); } String line; while ((line = reader.readLine()) != null) { writer.println(line); } }
python
def appliance_device_snmp_v3_users(self): """ Gets the ApplianceDeviceSNMPv3Users API client. Returns: ApplianceDeviceSNMPv3Users: """ if not self.__appliance_device_snmp_v3_users: self.__appliance_device_snmp_v3_users = ApplianceDeviceSNMPv3Users(self.__connection) return self.__appliance_device_snmp_v3_users
python
def unload(self): """ Overridable method called when a view is unloaded (either on view change or on application shutdown). Handles by default the unregistering of all event handlers previously registered by the view. """ self.is_loaded = False for evt in self._event_cache: self.context.unregister( evt['event'], evt['callback'], evt['selector']) self._event_cache = {}
java
public static <PS, SEG, S> UndoManager<List<PlainTextChange>> plainTextUndoManager( GenericStyledArea<PS, SEG, S> area, Duration preventMergeDelay) { return plainTextUndoManager(area, UndoManagerFactory.unlimitedHistoryFactory(), preventMergeDelay); }
python
def register_plugins(): """find any installed plugins and register them.""" if pkg_resources: # pragma: no cover for ep in pkg_resources.iter_entry_points('slam_plugins'): plugin = ep.load() # add any init options to the main init command if hasattr(plugin, 'init') and hasattr(plugin.init, '_arguments'): for arg in plugin.init._arguments: init.parser.add_argument(*arg[0], **arg[1]) init._arguments += plugin.init._arguments init._argnames += plugin.init._argnames plugins[ep.name] = plugin
java
public Observable<UUID> createCompositeEntityRoleAsync(UUID appId, String versionId, UUID cEntityId, CreateCompositeEntityRoleOptionalParameter createCompositeEntityRoleOptionalParameter) { return createCompositeEntityRoleWithServiceResponseAsync(appId, versionId, cEntityId, createCompositeEntityRoleOptionalParameter).map(new Func1<ServiceResponse<UUID>, UUID>() { @Override public UUID call(ServiceResponse<UUID> response) { return response.body(); } }); }
java
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { if (active) { if (log.isDebugEnabled()) log.debug("sessionDestroyed called for sessionId = " + httpSessionEvent.getSession().getId()); HttpSession session = httpSessionEvent.getSession(); HttpSessionWrapper wrapper = new HttpSessionWrapper(session); String name = wrapper.getResourceEntryPoint(); if (name != null) { HttpServletResourceEntryPoint resourceEntryPoint = HttpServletResourceEntryPointManager.getResourceEntryPoint(name); if (resourceEntryPoint != null) { resourceEntryPoint.onSessionTerminated(wrapper); } } } }
python
def get_value_from_user(sc): """ Prompts the user for a value for the symbol or choice 'sc'. For bool/tristate symbols and choices, provides a list of all the assignable values. """ if not sc.visibility: print(sc.name + " is not currently visible") return False prompt = "Value for {}".format(sc.name) if sc.type in (BOOL, TRISTATE): prompt += " (available: {})" \ .format(", ".join(TRI_TO_STR[val] for val in sc.assignable)) prompt += ": " val = input(prompt) # Automatically add a "0x" prefix for hex symbols, like the menuconfig # interface does. This isn't done when loading .config files, hence why # set_value() doesn't do it automatically. if sc.type == HEX and not val.startswith(("0x", "0X")): val = "0x" + val # Let Kconfiglib itself print a warning here if the value is invalid. We # could also disable warnings temporarily with # kconf.disable_warnings() / kconf.enable_warnings() and print our own # warning. return sc.set_value(val)
java
public void marshall(DeleteApnsVoipChannelRequest deleteApnsVoipChannelRequest, ProtocolMarshaller protocolMarshaller) { if (deleteApnsVoipChannelRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteApnsVoipChannelRequest.getApplicationId(), APPLICATIONID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
@NonNull public Caffeine<K, V> ticker(@NonNull Ticker ticker) { requireState(this.ticker == null, "Ticker was already set to %s", this.ticker); this.ticker = requireNonNull(ticker); return this; }
python
def _create_bam_region(paired, region, tmp_dir): """create temporal normal/tumor bam_file only with reads on that region""" tumor_name, normal_name = paired.tumor_name, paired.normal_name normal_bam = _slice_bam(paired.normal_bam, region, tmp_dir, paired.tumor_config) tumor_bam = _slice_bam(paired.tumor_bam, region, tmp_dir, paired.tumor_config) paired = PairedData(tumor_bam, tumor_name, normal_bam, normal_name, None, None, None) return paired
python
def on_message(self, message): """ Runs on a create_message event from websocket connection Args: message (dict): Full message from Discord websocket connection" """ if 'content' in message['d']: metadata = self._parse_metadata(message) message = Message(text=message['d']['content'], metadata=metadata).__dict__ logger.debug(message) self.baseplate.tell(message)
python
def _check_coop(self, pore, queue): r""" Method run in loop after every pore invasion. All connecting throats are now given access to the invading phase. Two throats with access to the invading phase can cooperatively fill any pores that they are both connected to, common pores. The invasion of theses throats connected to the common pore is handled elsewhere. """ net = self.project.network t_inv = 'throat.invasion_sequence' p_inv = 'pore.invasion_sequence' for throat in net.find_neighbor_throats(pores=pore): # A pore has just been invaded, all it's throats now have # An interface residing inside them if self[t_inv][throat] == -1: # If the throat is not the invading throat that gave access # to this pore, get the pores that this throat connects with a = set(net['throat.conns'][throat]) # Get a list of pre-calculated coop filling pressures for all # Throats this throat can coop fill with ts_Pc = self.tt_Pc.data[throat] # Network indices of throats that can act as filling pairs ts = self.tt_Pc.rows[throat] # If there are any potential coop filling throats if np.any(~np.isnan(ts_Pc)): ts_Pc = np.asarray(ts_Pc) ts = np.asarray(ts) ts = ts[~np.isnan(ts_Pc)] ts_Pc = ts_Pc[~np.isnan(ts_Pc)] # For each throat find the common pore and the uncommon # pores for i, t in enumerate(ts): # Find common pore (cP) and uncommon pores (uPs) b = set(net['throat.conns'][t]) cP = list(a.intersection(b)) uPs = list(a.symmetric_difference(b)) # If the common pore is not invaded but the others are # The potential coop filling event can now happen # Add the coop pressure to the queue if ((np.all(self[p_inv][uPs] > -1)) and (self[p_inv][cP] == -1)): # Coop pore filling fills the common pore # The throats that gave access are not invaded now # However, isolated throats between invaded pores # Are taken care of elsewhere... hq.heappush(queue, [ts_Pc[i], list(cP), 'pore'])
python
def run(self, from_email, recipients, message): """ This does the dirty work. Connects to Amazon SES via boto and fires off the message. :param str from_email: The email address the message will show as originating from. :param list recipients: A list of email addresses to send the message to. :param str message: The body of the message. """ self._open_ses_conn() try: # We use the send_raw_email func here because the Django # EmailMessage object we got these values from constructs all of # the headers and such. self.connection.send_raw_email( source=from_email, destinations=recipients, raw_message=dkim_sign(message), ) except SESAddressBlacklistedError, exc: # Blacklisted users are those which delivery failed for in the # last 24 hours. They'll eventually be automatically removed from # the blacklist, but for now, this address is marked as # undeliverable to. logger.warning( 'Attempted to email a blacklisted user: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESDomainEndsWithDotError, exc: # Domains ending in a dot are simply invalid. logger.warning( 'Invalid recipient, ending in dot: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESLocalAddressCharacterError, exc: # Invalid character, usually in the sender "name". logger.warning( 'Local address contains control or whitespace: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except SESIllegalAddressError, exc: # A clearly mal-formed address. logger.warning( 'Illegal address: %s' % recipients, exc_info=exc, extra={'trace': True} ) return False except Exception, exc: # Something else happened that we haven't explicitly forbade # retry attempts for. #noinspection PyUnresolvedReferences logger.error( 'Something went wrong; retrying: %s' % recipients, exc_info=exc, extra={'trace': True} ) self.retry(exc=exc) else: logger.info('An email has been successfully sent: %s' % recipients) # We shouldn't ever block long enough to see this, but here it is # just in case (for debugging?). return True
java
private String fixupAuthority(String uriAuthority, String charset) throws URIException { // Lowercase the host part of the uriAuthority; don't destroy any // userinfo capitalizations. Make sure no illegal characters in // domainlabel substring of the uri authority. if (uriAuthority != null) { // Get rid of any trailing escaped spaces: // http://www.archive.org%20. Rare but happens. // TODO: reevaluate: do IE or firefox do such mid-URI space-removal? // if not, we shouldn't either. while(uriAuthority.endsWith(ESCAPED_SPACE)) { uriAuthority = uriAuthority.substring(0,uriAuthority.length()-3); } // lowercase & IDN-punycode only the domain portion int atIndex = uriAuthority.indexOf(COMMERCIAL_AT); int portColonIndex = uriAuthority.indexOf(COLON,(atIndex<0)?0:atIndex); if(atIndex<0 && portColonIndex<0) { // most common case: neither userinfo nor port return fixupDomainlabel(uriAuthority); } else if (atIndex<0 && portColonIndex>-1) { // next most common: port but no userinfo String domain = fixupDomainlabel(uriAuthority.substring(0,portColonIndex)); String port = uriAuthority.substring(portColonIndex); return domain + port; } else if (atIndex>-1 && portColonIndex<0) { // uncommon: userinfo, no port String userinfo = ensureMinimalEscaping(uriAuthority.substring(0,atIndex+1),charset); String domain = fixupDomainlabel(uriAuthority.substring(atIndex+1)); return userinfo + domain; } else { // uncommon: userinfo, port String userinfo = ensureMinimalEscaping(uriAuthority.substring(0,atIndex+1),charset); String domain = fixupDomainlabel(uriAuthority.substring(atIndex+1,portColonIndex)); String port = uriAuthority.substring(portColonIndex); return userinfo + domain + port; } } return uriAuthority; }
python
def _render_cmd(cmd, cwd, template, saltenv='base', pillarenv=None, pillar_override=None): ''' If template is a valid template engine, process the cmd and cwd through that engine. ''' if not template: return (cmd, cwd) # render the path as a template using path_template_engine as the engine if template not in salt.utils.templates.TEMPLATE_REGISTRY: raise CommandExecutionError( 'Attempted to render file paths with unavailable engine ' '{0}'.format(template) ) kwargs = {} kwargs['salt'] = __salt__ if pillarenv is not None or pillar_override is not None: pillarenv = pillarenv or __opts__['pillarenv'] kwargs['pillar'] = _gather_pillar(pillarenv, pillar_override) else: kwargs['pillar'] = __pillar__ kwargs['grains'] = __grains__ kwargs['opts'] = __opts__ kwargs['saltenv'] = saltenv def _render(contents): # write out path to temp file tmp_path_fn = salt.utils.files.mkstemp() with salt.utils.files.fopen(tmp_path_fn, 'w+') as fp_: fp_.write(salt.utils.stringutils.to_str(contents)) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( tmp_path_fn, to_str=True, **kwargs ) salt.utils.files.safe_rm(tmp_path_fn) if not data['result']: # Failed to render the template raise CommandExecutionError( 'Failed to execute cmd with error: {0}'.format( data['data'] ) ) else: return data['data'] cmd = _render(cmd) cwd = _render(cwd) return (cmd, cwd)
java
public static <K, V> Pipes<K, V> of(final Map<K, Adapter<V>> registered) { Objects.requireNonNull(registered); final Pipes<K, V> pipes = new Pipes<>(); pipes.registered.putAll(registered); return pipes; }
java
public synchronized void setString(String value) throws SQLException { if (value == null) { throw Util.nullArgument("value"); } checkWritable(); setStringImpl(value); setReadable(true); setWritable(false); }
python
def to_json(self): """ Returns: str: """ data = dict() for key, value in self.__dict__.items(): if value: if hasattr(value, 'to_dict'): data[key] = value.to_dict() elif isinstance(value, datetime): data[key] = value.strftime('%Y-%m-%d %H:%M:%S') else: data[key] = value return json.dumps(data)
python
def get_indelcaller(d_or_c): """Retrieve string for indelcaller to use, or empty string if not specified. """ config = d_or_c if isinstance(d_or_c, dict) and "config" in d_or_c else d_or_c indelcaller = config["algorithm"].get("indelcaller", "") if not indelcaller: indelcaller = "" if isinstance(indelcaller, (list, tuple)): indelcaller = indelcaller[0] if (len(indelcaller) > 0) else "" return indelcaller
java
@Override public String filter(String value, String previousValue){ if(previousValue != null && value.length() > previousValue.length()) return value; return value.equals("0") || value.equals("0.0") ? "" : value; }
python
def find_mismatches(gene, sbjct_start, sbjct_seq, qry_seq, alternative_overlaps = []): """ This function finds mis matches between two sequeces. Depending on the the sequence type either the function find_codon_mismatches or find_nucleotid_mismatches are called, if the sequences contains both a promoter and a coding region both functions are called. The function can also call it self if alternative overlaps is give. All found mis matches are returned """ # Initiate the mis_matches list that will store all found mis matcehs mis_matches = [] # Find mis matches in RNA genes if gene in RNA_gene_list: mis_matches += find_nucleotid_mismatches(sbjct_start, sbjct_seq, qry_seq) else: # Check if the gene sequence is with a promoter regex = r"promoter_size_(\d+)(?:bp)" promtr_gene_objt = re.search(regex, gene) # Check for promoter sequences if promtr_gene_objt: # Get promoter length promtr_len = int(promtr_gene_objt.group(1)) # Extract promoter sequence, while considering gaps # --------agt-->---- # ---->? if sbjct_start <= promtr_len: #Find position in sbjct sequence where promoter ends promtr_end = 0 nuc_count = sbjct_start - 1 for i in range(len(sbjct_seq)): promtr_end += 1 if sbjct_seq[i] != "-": nuc_count += 1 if nuc_count == promtr_len: break # Check if only a part of the promoter is found #--------agt-->---- # ---- promtr_sbjct_start = -1 if nuc_count < promtr_len: promtr_sbjct_start = nuc_count - promtr_len # Get promoter part of subject and query sbjct_promtr_seq = sbjct_seq[:promtr_end] qry_promtr_seq = qry_seq[:promtr_end] # For promoter part find nucleotide mis matches mis_matches += find_nucleotid_mismatches(promtr_sbjct_start, sbjct_promtr_seq, qry_promtr_seq, promoter = True) # Check if gene is also found #--------agt-->---- # ----------- if (sbjct_start + len(sbjct_seq.replace("-", ""))) > promtr_len: sbjct_gene_seq = sbjct_seq[promtr_end:] qry_gene_seq = qry_seq[promtr_end:] sbjct_gene_start = 1 # Find mismatches in gene part mis_matches += find_codon_mismatches(sbjct_gene_start, sbjct_gene_seq, qry_gene_seq) # No promoter, only gene is found #--------agt-->---- # ----- else: sbjct_gene_start = sbjct_start - promtr_len # Find mismatches in gene part mis_matches += find_codon_mismatches(sbjct_gene_start, sbjct_seq, qry_seq) else: # Find mismatches in gene mis_matches += find_codon_mismatches(sbjct_start, sbjct_seq, qry_seq) # Find mismatches in alternative overlaps if any for overlap in alternative_overlaps: mis_matches += find_mismatches(gene, overlap[0], overlap[2], overlap[3]) return mis_matches
python
def restore(mongo_user, mongo_password, backup_tbz_path, backup_directory_output_path="/tmp/mongo_dump", drop_database=False, cleanup=True, silent=False, skip_system_and_user_files=False): """ Runs mongorestore with source data from the provided .tbz backup, using the provided username and password. The contents of the .tbz will be dumped into the provided backup directory, and that folder will be deleted after a successful mongodb restore unless cleanup is set to False. Note: the skip_system_and_user_files is intended for use with the changes in user architecture introduced in mongodb version 2.6. Warning: Setting drop_database to True will drop the ENTIRE CURRENTLY RUNNING DATABASE before restoring. Mongorestore requires a running mongod process, in addition the provided user must have restore permissions for the database. A mongolia superuser will have more than adequate permissions, but a regular user may not. By default this function will clean up the output of the untar operation. """ if not path.exists(backup_tbz_path): raise Exception("the provided tar file %s does not exist." % (backup_tbz_path)) untarbz(backup_tbz_path, backup_directory_output_path, silent=silent) if skip_system_and_user_files: system_and_users_path = "%s/admin" % backup_directory_output_path if path.exists(system_and_users_path): rmtree(system_and_users_path) mongorestore(mongo_user, mongo_password, backup_directory_output_path, drop_database=drop_database, silent=silent) if cleanup: rmtree(backup_directory_output_path)
java
public void script(String line, DispatchCallback callback) { if (sqlLine.getScriptOutputFile() == null) { startScript(line, callback); } else { stopScript(line, callback); } }
java
public String getFileSystemTypeLabel() { final StringBuilder sb = new StringBuilder(FILE_SYSTEM_TYPE_LENGTH); for (int i=0; i < FILE_SYSTEM_TYPE_LENGTH; i++) { sb.append ((char) get8(getFileSystemTypeLabelOffset() + i)); } return sb.toString(); }
python
def clear_caches(self): """ Clears the Caches for all model elements """ for element_name in dir(self.components): element = getattr(self.components, element_name) if hasattr(element, 'cache_val'): delattr(element, 'cache_val')
java
public int commandToDocType(String strCommand) { if (UserInfo.VERBOSE_MAINT_SCREEN.equalsIgnoreCase(strCommand)) return UserInfo.VERBOSE_MAINT_MODE; if (UserInfo.LOGIN_SCREEN.equalsIgnoreCase(strCommand)) return UserInfo.LOGIN_SCREEN_MODE; if (UserInfo.ENTRY_SCREEN.equalsIgnoreCase(strCommand)) return UserInfo.ENTRY_SCREEN_MODE; if (UserInfo.PREFERENCES_SCREEN.equalsIgnoreCase(strCommand)) return UserInfo.PREFERENCES_SCREEN_MODE; if (UserInfo.PASSWORD_CHANGE_SCREEN.equalsIgnoreCase(strCommand)) return UserInfo.PASSWORD_CHANGE_SCREEN_MODE; return super.commandToDocType(strCommand); }
java
public void genArgs(List<JCExpression> trees, List<Type> pts) { for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) { genExpr(l.head, pts.head).load(); pts = pts.tail; } // require lists be of same length Assert.check(pts.isEmpty()); }
java
public void setAdapter(final BaseCircularViewAdapter adapter) { mAdapter = adapter; if (mAdapter != null) { mAdapter.registerDataSetObserver(mAdapterDataSetObserver); } postInvalidate(); }
python
def authorize_url(self): """ Build the authorization url and save the state. Return the authorization url """ url, self.state = self.oauth.authorization_url( '%sauthorize' % OAUTH_URL) return url
python
def query_user_info(user): """ Returns the scraped user data from a twitter user page. :param user: the twitter user to web scrape its twitter page info """ try: user_info = query_user_page(INIT_URL_USER.format(u=user)) if user_info: logger.info(f"Got user information from username {user}") return user_info except KeyboardInterrupt: logger.info("Program interrupted by user. Returning user information gathered so far...") except BaseException: logger.exception("An unknown error occurred! Returning user information gathered so far...") logger.info(f"Got user information from username {user}") return user_info
python
def _delete(self, **kwargs): """wrapped with delete, override that in a subclass to customize """ requests_params = self._handle_requests_params(kwargs) delete_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] # Check the generation for match before delete force = self._check_force_arg(kwargs.pop('force', True)) if not force: self._check_generation() response = session.delete(delete_uri, **requests_params) if response.status_code == 200: self.__dict__ = {'deleted': True}
python
def error_message_and_exit(message, error_result): """Prints error messages in blue, the failed task result and quits.""" if message: error_message(message) puts(json.dumps(error_result, indent=2)) sys.exit(1)
python
def dictdict_to_listdict(dictgraph): """Transforms a dict-dict graph representation into a adjacency dictionary representation (list-dict) :param dictgraph: dictionary mapping vertices to dictionary such that dictgraph[u][v] is weight of arc (u,v) :complexity: linear :returns: tuple with graph (listdict), name_to_node (dict), node_to_name (list) """ n = len(dictgraph) # vertices node_to_name = [name for name in dictgraph] # bijection indices <-> names node_to_name.sort() # to make it more readable name_to_node = {} for i in range(n): name_to_node[node_to_name[i]] = i sparse = [{} for _ in range(n)] # build sparse graph for u in dictgraph: for v in dictgraph[u]: sparse[name_to_node[u]][name_to_node[v]] = dictgraph[u][v] return sparse, name_to_node, node_to_name
python
def get_site_name(request): """Return the domain:port part of the URL without scheme. Eg: facebook.com, 127.0.0.1:8080, etc. """ urlparts = request.urlparts return ':'.join([urlparts.hostname, str(urlparts.port)])
java
public final <R> Ix<R> map(IxFunction<? super T, ? extends R> mapper) { return new IxMap<T, R>(this, mapper); }