language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected void cleanFile(String path) { try { PrintWriter writer; writer = new PrintWriter(path); writer.print(""); writer.close(); } catch (FileNotFoundException e) { throw new RuntimeException("An error occurred while cleaning the file: " + e.getMessage(), e); } }
python
def _extract_numbers(arg: Message_T) -> List[float]: """Extract all numbers (integers and floats) from a message-like object.""" s = str(arg) return list(map(float, re.findall(r'[+-]?(\d*\.?\d+|\d+\.?\d*)', s)))
java
public BigFloat multiply(BigFloat x) { if (x.isSpecial()) return x.multiply(this); Context c = max(context, x.context); return c.valueOf(value.multiply(x.value, c.mathContext)); }
java
private ARCRecordMetaData computeMetaData(List<String> keys, List<String> values, String v, String origin, long offset, final String identifier) throws IOException { if (keys.size() != values.size()) { List<String> originalValues = values; if (!isStrict()) { values = fixSpaceInURL(values, keys.size()); // If values still doesn't match key size, try and do // further repair. if (keys.size() != values.size()) { // Early ARCs had a space in mimetype. if (values.size() == (keys.size() + 1) && values.get(4).toLowerCase().startsWith("charset=")) { List<String> nuvalues = new ArrayList<String>(keys.size()); nuvalues.add(0, values.get(0)); nuvalues.add(1, values.get(1)); nuvalues.add(2, values.get(2)); nuvalues.add(3, values.get(3) + values.get(4)); nuvalues.add(4, values.get(5)); values = nuvalues; } else if((values.size() + 1) == keys.size() && isLegitimateIPValue(values.get(1)) && isDate(values.get(2)) && isNumber(values.get(3))) { // Mimetype is empty. List<String> nuvalues = new ArrayList<String>(keys.size()); nuvalues.add(0, values.get(0)); nuvalues.add(1, values.get(1)); nuvalues.add(2, values.get(2)); nuvalues.add(3, "-"); nuvalues.add(4, values.get(3)); values = nuvalues; } } } if (keys.size() != values.size()) { throw new IOException("Size of field name keys does" + " not match count of field values: " + values); } // Note that field was fixed on stderr. System.err.println(Level.WARNING.toString() + "Fixed spaces in metadata line at " + "offset " + offset + " Original: " + originalValues + ", New: " + values); } Map<String, Object> headerFields = new HashMap<String, Object>(keys.size() + 2); for (int i = 0; i < keys.size(); i++) { headerFields.put(keys.get(i), values.get(i)); } // Add a check for tabs in URLs. If any, replace with '%09'. // See https://sourceforge.net/tracker/?group_id=73833&atid=539099&func=detail&aid=1010966, // [ 1010966 ] crawl.log has URIs with spaces in them. String url = (String)headerFields.get(URL_FIELD_KEY); if (url != null && url.indexOf('\t') >= 0) { headerFields.put(URL_FIELD_KEY, TextUtils.replaceAll("\t", url, "%09")); } headerFields.put(VERSION_FIELD_KEY, v); headerFields.put(ORIGIN_FIELD_KEY, origin); headerFields.put(ABSOLUTE_OFFSET_KEY, new Long(offset)); return new ARCRecordMetaData(identifier, headerFields); }
python
def _augment(graph, capacity, flow, source, target): """find a shortest augmenting path """ n = len(graph) A = [0] * n # A[v] = min residual cap. on path source->v augm_path = [None] * n # None = node was not visited yet Q = deque() # BFS Q.append(source) augm_path[source] = source A[source] = float('inf') while Q: u = Q.popleft() for v in graph[u]: cuv = capacity[u][v] residual = cuv - flow[u][v] if residual > 0 and augm_path[v] is None: augm_path[v] = u # store predecessor A[v] = min(A[u], residual) if v == target: break else: Q.append(v) return (augm_path, A[target])
java
private boolean performDialogOperation(HttpServletRequest request) throws CmsException { List<CmsPropertyDefinition> propertyDef = getCms().readAllPropertyDefinitions(); boolean useTempfileProject = Boolean.valueOf(getParamUsetempfileproject()).booleanValue(); try { if (useTempfileProject) { switchToTempProject(); } Map<String, CmsProperty> activeProperties = getActiveProperties(); String activeTab = getActiveTabName(); List<CmsProperty> propertiesToWrite = new ArrayList<CmsProperty>(); // check all property definitions of the resource for new values Iterator<CmsPropertyDefinition> i = propertyDef.iterator(); while (i.hasNext()) { CmsPropertyDefinition curPropDef = i.next(); String propName = CmsEncoder.escapeXml(curPropDef.getName()); String valueStructure = null; String valueResource = null; if (key(Messages.GUI_PROPERTIES_INDIVIDUAL_0).equals(activeTab)) { // get parameters from the structure tab valueStructure = request.getParameter(PREFIX_VALUE + propName); valueResource = request.getParameter(PREFIX_RESOURCE + propName); if ((valueStructure != null) && !"".equals(valueStructure.trim()) && valueStructure.equals(valueResource)) { // the resource value was shown/entered in input field, set structure value to empty String valueStructure = ""; } } else { // get parameters from the resource tab valueStructure = request.getParameter(PREFIX_STRUCTURE + propName); valueResource = request.getParameter(PREFIX_VALUE + propName); } // check values for blanks and null if (valueStructure != null) { valueStructure = valueStructure.trim(); } if (valueResource != null) { valueResource = valueResource.trim(); } // create new CmsProperty object to store CmsProperty newProperty = new CmsProperty(); newProperty.setName(curPropDef.getName()); newProperty.setStructureValue(valueStructure); newProperty.setResourceValue(valueResource); // get the old property values CmsProperty oldProperty = activeProperties.get(curPropDef.getName()); if (oldProperty == null) { // property was not set, create new empty property object oldProperty = new CmsProperty(); oldProperty.setName(curPropDef.getName()); } boolean writeStructureValue = false; boolean writeResourceValue = false; String oldValue = oldProperty.getStructureValue(); String newValue = newProperty.getStructureValue(); // write the structure value if the existing structure value is not null and we want to delete the structure value writeStructureValue = ((oldValue != null) && newProperty.isDeleteStructureValue()); // or if we want to write a value which is neither the delete value or an empty value writeStructureValue |= !newValue.equals(oldValue) && !"".equalsIgnoreCase(newValue) && !CmsProperty.DELETE_VALUE.equalsIgnoreCase(newValue); // set the structure value explicitly to null to leave it as is in the database if (!writeStructureValue) { newProperty.setStructureValue(null); } oldValue = oldProperty.getResourceValue(); newValue = newProperty.getResourceValue(); // write the resource value if the existing resource value is not null and we want to delete the resource value writeResourceValue = ((oldValue != null) && newProperty.isDeleteResourceValue()); // or if we want to write a value which is neither the delete value or an empty value writeResourceValue |= !newValue.equals(oldValue) && !"".equalsIgnoreCase(newValue) && !CmsProperty.DELETE_VALUE.equalsIgnoreCase(newValue); // set the resource value explicitly to null to leave it as is in the database if (!writeResourceValue) { newProperty.setResourceValue(null); } if (writeStructureValue || writeResourceValue) { // add property to list only if property values have changed propertiesToWrite.add(newProperty); } } if (propertiesToWrite.size() > 0) { // lock resource if autolock is enabled checkLock(getParamResource()); //write the new property values getCms().writePropertyObjects(getParamResource(), propertiesToWrite); } } finally { if (useTempfileProject) { switchToCurrentProject(); } } return true; }
java
private static ByteBuf writePayload( final ByteBufAllocator alloc, final long requestId, final MessageType messageType, final byte[] payload) { final int frameLength = HEADER_LENGTH + REQUEST_ID_SIZE + payload.length; final ByteBuf buf = alloc.ioBuffer(frameLength + Integer.BYTES); buf.writeInt(frameLength); writeHeader(buf, messageType); buf.writeLong(requestId); buf.writeBytes(payload); return buf; }
java
public TransformersSubRegistration getDomainRegistration(final ModelVersionRange range) { final PathAddress address = PathAddress.EMPTY_ADDRESS; return new TransformersSubRegistrationImpl(range, domain, address); }
python
def _is_viable_phone_number(number): """Checks to see if a string could possibly be a phone number. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance - but does assume that leading non-number symbols have been removed, such as by the method _extract_possible_number. Arguments: number -- string to be checked for viability as a phone number Returns True if the number could be a phone number of some sort, otherwise False """ if len(number) < _MIN_LENGTH_FOR_NSN: return False match = fullmatch(_VALID_PHONE_NUMBER_PATTERN, number) return bool(match)
java
public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) { super.initialize(subject, callbackHandler, sharedState, options); Properties props = loadProperties((String) options.get("file")); initWithProps(props); }
python
def strip_accents(string): """ Strip all the accents from the string """ return u''.join( (character for character in unicodedata.normalize('NFD', string) if unicodedata.category(character) != 'Mn'))
python
def factorize( self, na_sentinel: int = -1, ) -> Tuple[np.ndarray, ABCExtensionArray]: """ Encode the extension array as an enumerated type. Parameters ---------- na_sentinel : int, default -1 Value to use in the `labels` array to indicate missing values. Returns ------- labels : ndarray An integer NumPy array that's an indexer into the original ExtensionArray. uniques : ExtensionArray An ExtensionArray containing the unique values of `self`. .. note:: uniques will *not* contain an entry for the NA value of the ExtensionArray if there are any missing values present in `self`. See Also -------- pandas.factorize : Top-level factorize method that dispatches here. Notes ----- :meth:`pandas.factorize` offers a `sort` keyword as well. """ # Impelmentor note: There are two ways to override the behavior of # pandas.factorize # 1. _values_for_factorize and _from_factorize. # Specify the values passed to pandas' internal factorization # routines, and how to convert from those values back to the # original ExtensionArray. # 2. ExtensionArray.factorize. # Complete control over factorization. from pandas.core.algorithms import _factorize_array arr, na_value = self._values_for_factorize() labels, uniques = _factorize_array(arr, na_sentinel=na_sentinel, na_value=na_value) uniques = self._from_factorized(uniques, self) return labels, uniques
python
def add_blacklisted_directories(self, directories, remove_from_stored_directories=True): """ Adds `directories` to be blacklisted. Blacklisted directories will not be returned or searched recursively when calling the `collect_directories` method. `directories` may be a single instance or an iterable. Recommend passing in absolute paths, but method will try to convert to absolute paths based on the current working directory. If `remove_from_stored_directories` is true, all `directories` will be removed from `self.plugin_directories` """ absolute_paths = util.to_absolute_paths(directories) self.blacklisted_directories.update(absolute_paths) if remove_from_stored_directories: plug_dirs = self.plugin_directories plug_dirs = util.remove_from_set(plug_dirs, directories)
python
def _POTUpdateBuilder(env, **kw): """ Creates `POTUpdate` builder object """ import SCons.Action from SCons.Tool.GettextCommon import _POTargetFactory kw['action'] = SCons.Action.Action(_update_pot_file, None) kw['suffix'] = '$POTSUFFIX' kw['target_factory'] = _POTargetFactory(env, alias='$POTUPDATE_ALIAS').File kw['emitter'] = _pot_update_emitter return _POTBuilder(**kw)
python
def group_batches(xs): """Group samples into batches for simultaneous variant calling. Identify all samples to call together: those in the same batch and variant caller. Pull together all BAM files from this batch and process together, Provide details to pull these finalized files back into individual expected files. Only batches files if joint calling not specified. """ def _caller_batches(data): caller = tz.get_in(("config", "algorithm", "variantcaller"), data) jointcaller = tz.get_in(("config", "algorithm", "jointcaller"), data) batch = tz.get_in(("metadata", "batch"), data) if not jointcaller else None return caller, batch def _prep_data(data, items): data["region_bams"] = [x["region_bams"] for x in items] return data return _group_batches_shared(xs, _caller_batches, _prep_data)
python
def process_entries( self, omimids, transform, included_fields=None, graph=None, limit=None, globaltt=None ): """ Given a list of omim ids, this will use the omim API to fetch the entries, according to the ```included_fields``` passed as a parameter. If a transformation function is supplied, this will iterate over each entry, and either add the results to the supplied ```graph``` or will return a set of processed entries that the calling function can further iterate. If no ```included_fields``` are provided, this will simply fetch the basic entry from omim, which includes an entry's: prefix, mimNumber, status, and titles. :param omimids: the set of omim entry ids to fetch using their API :param transform: Function to transform each omim entry when looping :param included_fields: A set of what fields are required to retrieve from the API :param graph: the graph to add the transformed data into :return: """ omimparams = {} # add the included_fields as parameters if included_fields is not None and included_fields: omimparams['include'] = ','.join(included_fields) processed_entries = list() # scrub any omim prefixes from the omimids before processing # cleanomimids = set() # for omimid in omimids: # scrubbed = str(omimid).split(':')[-1] # if re.match(r'^\d+$', str(scrubbed)): # cleanomimids.update(scrubbed) # omimids = list(cleanomimids) cleanomimids = [o.split(':')[-1] for o in omimids] diff = set(omimids) - set(cleanomimids) if diff: LOG.warning('OMIM has %i dirty bits see"\n %s', len(diff), str(diff)) omimids = cleanomimids else: cleanomimids = list() acc = 0 # for counting # note that you can only do request batches of 20 # see info about "Limits" at http://omim.org/help/api # TODO 2017 May seems a majority of many groups of 20 # are producing python None for RDF triple Objects groupsize = 20 if not self.test_mode and limit is not None: # just in case the limit is larger than the number of records, maxit = limit if limit > len(omimids): maxit = len(omimids) else: maxit = len(omimids) while acc < maxit: end = min((maxit, acc + groupsize)) # iterate through the omim ids list, # and fetch from the OMIM api in batches of 20 if self.test_mode: intersect = list( set([str(i) for i in self.test_ids]) & set(omimids[acc:end])) # some of the test ids are in the omimids if intersect: LOG.info("found test ids: %s", intersect) omimparams.update({'mimNumber': ','.join(intersect)}) else: acc += groupsize continue else: omimparams.update({'mimNumber': ','.join(omimids[acc:end])}) url = OMIMAPI + urllib.parse.urlencode(omimparams) try: req = urllib.request.urlopen(url) except HTTPError as e: # URLError? LOG.warning('fetching: %s', url) error_msg = e.read() if re.search(r'The API key: .* is invalid', str(error_msg)): msg = "API Key not valid" raise HTTPError(url, e.code, msg, e.hdrs, e.fp) LOG.error("Failed with: %s", str(error_msg)) break resp = req.read().decode() acc += groupsize myjson = json.loads(resp) # snag a copy with open('./raw/omim/_' + str(acc) + '.json', 'w') as fp: json.dump(myjson, fp) entries = myjson['omim']['entryList'] for e in entries: # apply the data transformation, and save it to the graph processed_entry = transform(e, graph, globaltt) if processed_entry is not None: processed_entries.append(processed_entry) # ### end iterating over batch of entries return processed_entries
java
private void addEPStatementListener(UpdateListener listener) { if (this.subscriber == null) { if (epStatement != null) { epStatement.addListener(listener); } } }
java
protected void writeContent(String requestedPath, HttpServletRequest request, HttpServletResponse response) throws IOException, ResourceNotFoundException { // Send gzipped resource if user agent supports it. int idx = requestedPath.indexOf(BundleRenderer.GZIP_PATH_PREFIX); if (idx != -1) { requestedPath = JawrConstant.URL_SEPARATOR + requestedPath.substring(idx + BundleRenderer.GZIP_PATH_PREFIX.length(), requestedPath.length()); if (isValidRequestedPath(requestedPath)) { response.setHeader(CONTENT_ENCODING, GZIP); bundlesHandler.streamBundleTo(requestedPath, response.getOutputStream()); } else { throw new ResourceNotFoundException(requestedPath); } } else { // In debug mode, we take in account the image generated from a // StreamGenerator like classpath Image generator // The following code will rewrite the URL path for the generated // images, // because in debug mode, we are retrieving the CSS resources // directly from the webapp // and if the CSS contains generated images, we should rewrite the // URL. BinaryResourcesHandler imgRsHandler = (BinaryResourcesHandler) servletContext .getAttribute(JawrConstant.BINARY_CONTEXT_ATTRIBUTE); if (imgRsHandler != null && this.jawrConfig.isDebugModeOn() && resourceType.equals(JawrConstant.CSS_TYPE)) { handleGeneratedCssInDebugMode(requestedPath, request, response, imgRsHandler); } else { if (isValidRequestedPath(requestedPath)) { Writer out = response.getWriter(); bundlesHandler.writeBundleTo(requestedPath, out); } else { throw new ResourceNotFoundException(requestedPath); } } } }
java
@Help(help = "Get the PhysicalNetworkFunctionRecord of a NetworkServiceRecord with specific id") public PhysicalNetworkFunctionRecord getPhysicalNetworkFunctionRecord( final String idNsr, final String idPnfr) throws SDKException { String url = idNsr + "/pnfrecords" + "/" + idPnfr; return (PhysicalNetworkFunctionRecord) requestGetWithStatusAccepted(url, PhysicalNetworkFunctionRecord.class); }
python
def _execute_batch(self, actions): """ Execute a single batch of Actions. For each action that has a problem, we annotate the action with the error information for that action, and we return the number of successful actions in the batch. :param actions: the list of Action objects to be executed :return: count of successful actions """ wire_form = [a.wire_dict() for a in actions] if self.test_mode: result = self.make_call("/action/%s?testOnly=true" % self.org_id, wire_form) else: result = self.make_call("/action/%s" % self.org_id, wire_form) body = result.json() if body.get("errors", None) is None: if body.get("result") != "success": if self.logger: self.logger.warning("Server action result: no errors, but no success:\n%s", body) return len(actions) try: if body.get("result") == "success": if self.logger: self.logger.warning("Server action result: errors, but success report:\n%s", body) for error in body["errors"]: actions[error["index"]].report_command_error(error) except: raise ClientError(str(body), result) return body.get("completed", 0)
java
public void setHitCount(IDbgpSession session, int value) throws CoreException { synchronized (sessions) { PerSessionInfo info = (PerSessionInfo) sessions.get(session); if (info == null) { info = new PerSessionInfo(); sessions.put(session, info); } info.hitCount = value; } }
python
def _add_hash(cls, attrs): """ Add a hash method to *cls*. """ cls.__hash__ = _make_hash(attrs, frozen=False, cache_hash=False) return cls
python
def CharacterData(self, data): ''' Expat character data event handler ''' if data.strip(): data = data.encode() if not self.data: self.data = data else: self.data += data
java
private static List<String> maskNull(List<String> pTypes) { return (pTypes == null) ? Collections.<String>emptyList() : pTypes; }
python
def default_token_user_loader(self, token): """ Default token user loader Accepts a token and decodes it checking signature and expiration. Then loads user by id from the token to see if account is not locked. If all is good, returns user record, otherwise throws an exception. :param token: str, token string :return: boiler.user.models.User """ try: data = self.decode_token(token) except jwt.exceptions.DecodeError as e: raise x.JwtDecodeError(str(e)) except jwt.ExpiredSignatureError as e: raise x.JwtExpired(str(e)) user = self.get(data['user_id']) if not user: msg = 'No user with such id [{}]' raise x.JwtNoUser(msg.format(data['user_id'])) if user.is_locked(): msg = 'This account is locked' raise x.AccountLocked(msg, locked_until=user.locked_until) if self.require_confirmation and not user.email_confirmed: msg = 'Please confirm your email address [{}]' raise x.EmailNotConfirmed( msg.format(user.email_secure), email=user.email ) # test token matches the one on file if not token == user._token: raise x.JwtTokenMismatch('The token does not match our records') # return on success return user
python
def _check_install(self): """Check if tlgu installed, if not install it.""" try: subprocess.check_output(['which', 'tlgu']) except Exception as exc: logger.info('TLGU not installed: %s', exc) logger.info('Installing TLGU.') if not subprocess.check_output(['which', 'gcc']): logger.error('GCC seems not to be installed.') else: tlgu_path_rel = '~/cltk_data/greek/software/greek_software_tlgu' tlgu_path = os.path.expanduser(tlgu_path_rel) if not self.testing: print('Do you want to install TLGU?') print('To continue, press Return. To exit, Control-C.') input() else: print('Automated or test build, skipping keyboard input confirmation for installation of TLGU.') try: command = 'cd {0} && make install'.format(tlgu_path) print('Going to run command:', command) p_out = subprocess.call(command, shell=True) if p_out == 0: logger.info('TLGU installed.') else: logger.error('TLGU install without sudo failed.') except Exception as exc: logger.error('TLGU install failed: %s', exc) else: # for Linux needing root access to '/usr/local/bin' if not self.testing: print('Could not install without root access. Do you want to install TLGU with sudo?') command = 'cd {0} && sudo make install'.format(tlgu_path) print('Going to run command:', command) print('To continue, press Return. To exit, Control-C.') input() p_out = subprocess.call(command, shell=True) else: command = 'cd {0} && sudo make install'.format(tlgu_path) p_out = subprocess.call(command, shell=True) if p_out == 0: logger.info('TLGU installed.') else: logger.error('TLGU install with sudo failed.')
java
private Set<String> getColumnsOfEmbeddableAndComputeEmbeddableNullness(String embeddable) { Set<String> columnsOfEmbeddable = new HashSet<String>(); boolean hasOnlyNullColumns = true; for ( String selectableColumn : columns ) { if ( !isColumnPartOfEmbeddable( embeddable, selectableColumn ) ) { continue; } columnsOfEmbeddable.add( selectableColumn ); if ( hasOnlyNullColumns && tuple.get( selectableColumn ) != null ) { hasOnlyNullColumns = false; } } if ( hasOnlyNullColumns ) { nullEmbeddables.add( embeddable ); } return columnsOfEmbeddable; }
python
def check_role(*roles, **args_map): """ It's just like has_role, but it's a decorator. And it'll check request.user """ def f1(func, roles=roles): @wraps(func) def f2(*args, **kwargs): from uliweb import request, error arguments = {} for k, v in args_map.items(): if v in kwargs: arguments[k] = kwargs[v] if not has_role(request.user, *roles, **arguments): error(_("You have no roles to visit this page.")) return func(*args, **kwargs) return f2 return f1
java
public String applyTransletNamePattern(String transletName, boolean absolutely) { DefaultSettings defaultSettings = assistantLocal.getDefaultSettings(); if (defaultSettings == null) { return transletName; } if (StringUtils.startsWith(transletName, ActivityContext.NAME_SEPARATOR_CHAR)) { if (absolutely) { return transletName; } transletName = transletName.substring(1); } if (defaultSettings.getTransletNamePrefix() == null && defaultSettings.getTransletNameSuffix() == null) { return transletName; } StringBuilder sb = new StringBuilder(); if (defaultSettings.getTransletNamePrefix() != null) { sb.append(defaultSettings.getTransletNamePrefix()); } if (transletName != null) { sb.append(transletName); } if (defaultSettings.getTransletNameSuffix() != null) { sb.append(defaultSettings.getTransletNameSuffix()); } return sb.toString(); }
java
protected Message createMessage(ConnectionContext context, BasicMessage basicMessage) throws JMSException { return createMessage(context, basicMessage, null); }
java
public List<CorporationMiningObserverResponse> getCorporationCorporationIdMiningObserversObserverId( Integer corporationId, Long observerId, String datasource, String ifNoneMatch, Integer page, String token) throws ApiException { ApiResponse<List<CorporationMiningObserverResponse>> resp = getCorporationCorporationIdMiningObserversObserverIdWithHttpInfo( corporationId, observerId, datasource, ifNoneMatch, page, token); return resp.getData(); }
python
def list_object_versions(Bucket, Delimiter=None, EncodingType=None, Prefix=None, region=None, key=None, keyid=None, profile=None): ''' List objects in a given S3 bucket. Returns a list of objects. CLI Example: .. code-block:: bash salt myminion boto_s3_bucket.list_object_versions mybucket ''' try: Versions = [] DeleteMarkers = [] args = {'Bucket': Bucket} args.update({'Delimiter': Delimiter}) if Delimiter else None args.update({'EncodingType': EncodingType}) if Delimiter else None args.update({'Prefix': Prefix}) if Prefix else None conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) IsTruncated = True while IsTruncated: ret = conn.list_object_versions(**args) IsTruncated = ret.get('IsTruncated', False) if IsTruncated in ('True', 'true', True): args['KeyMarker'] = ret['NextKeyMarker'] args['VersionIdMarker'] = ret['NextVersionIdMarker'] Versions += ret.get('Versions', []) DeleteMarkers += ret.get('DeleteMarkers', []) return {'Versions': Versions, 'DeleteMarkers': DeleteMarkers} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
java
public boolean validateModcaString4(String modcaString4, DiagnosticChain diagnostics, Map<Object, Object> context) { boolean result = validateModcaString4_MinLength(modcaString4, diagnostics, context); if (result || diagnostics != null) result &= validateModcaString4_MaxLength(modcaString4, diagnostics, context); return result; }
java
public static JSONObject loadPublicJSONFile(final String publicDirectory, final String file) { final File dir = Environment.getExternalStoragePublicDirectory(publicDirectory); return loadJSONFile(dir, file); }
java
public void marshall(Service service, ProtocolMarshaller protocolMarshaller) { if (service == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(service.getId(), ID_BINDING); protocolMarshaller.marshall(service.getArn(), ARN_BINDING); protocolMarshaller.marshall(service.getName(), NAME_BINDING); protocolMarshaller.marshall(service.getNamespaceId(), NAMESPACEID_BINDING); protocolMarshaller.marshall(service.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(service.getInstanceCount(), INSTANCECOUNT_BINDING); protocolMarshaller.marshall(service.getDnsConfig(), DNSCONFIG_BINDING); protocolMarshaller.marshall(service.getHealthCheckConfig(), HEALTHCHECKCONFIG_BINDING); protocolMarshaller.marshall(service.getHealthCheckCustomConfig(), HEALTHCHECKCUSTOMCONFIG_BINDING); protocolMarshaller.marshall(service.getCreateDate(), CREATEDATE_BINDING); protocolMarshaller.marshall(service.getCreatorRequestId(), CREATORREQUESTID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
static public String toUri(Object o) { if (o == null) { return null; } String uri = o.toString(); if (uri.startsWith("/")) { // Treat two slashes as server-relative if (uri.startsWith("//")) { uri = uri.substring(1); } else { FacesContext fContext = FacesContext.getCurrentInstance(); uri = fContext.getExternalContext().getRequestContextPath() + uri; } } return uri; }
python
def _handle_cancel_notification(self, msg_id): """Handle a cancel notification from the client.""" request_future = self._client_request_futures.pop(msg_id, None) if not request_future: log.warn("Received cancel notification for unknown message id %s", msg_id) return # Will only work if the request hasn't started executing if request_future.cancel(): log.debug("Cancelled request with id %s", msg_id)
java
public void createCertificate(InputStream certStream) throws BatchErrorException, IOException, CertificateException, NoSuchAlgorithmException { createCertificate(certStream, null); }
java
public static <T> T fromJson(String json, Class<T> T) { return getGson().fromJson(json, T); }
java
public AptControlInterface getMostDerivedInterface() { // // Walk up ControlInterface chain looking for the 1st instance annotated // w/ @ControlInterface (as opposed to @ControlExtension) // // REVIEW: TBD rules for inheritance of @ControlInterface will affect this. // Probably need to keep walking and examine each @ControlInterface in the chain. // Run all checkers in chain? Make checkers responsible for invoking their base // class-defined checkers? // AptControlInterface ancestor = getSuperClass(); while (ancestor != null) { if (!ancestor.isExtension()) break; ancestor = ancestor.getSuperClass(); } return ancestor; }
java
public GedRenderer<? extends GedObject> create( final GedObject gedObject, final RenderingContext renderingContext) { if (gedObject != null) { final RendererBuilder builder = builders.get(gedObject.getClass()); if (builder != null) { return builder.build(gedObject, this, renderingContext); } } return new DefaultRenderer( gedObject, this, renderingContext); }
python
def call_api_fetch(self, params, get_latest_only=True): """ GET https: // myserver / piwebapi / assetdatabases / D0NxzXSxtlKkGzAhZfHOB - KAQLhZ5wrU - UyRDQnzB_zGVAUEhMQUZTMDRcTlVHUkVFTg HTTP / 1.1 Host: myserver Accept: application / json""" output_format = 'application/json' url_string = self.request_info.url_string() # passing the username and required output format headers_list = {"Accept": output_format, "Host": self.request_info.host} try: hub_result = requests.get(url_string, headers=headers_list, timeout=10.000, verify=False) if hub_result.ok == False: raise ConnectionRefusedError("Connection to Triangulum hub refused: " + hub_result.reason) except: raise ConnectionError("Error connecting to Triangulum hub - check internet connection.") result = {} result_content_json = hub_result.json() result['ok'] = hub_result.ok result['content'] = json.dumps(result_content_json) if "Items" in result_content_json: available_matches = len(result_content_json['Items']) else: available_matches = 1 # No Date params allowed in call to hub, so apply get latest only to hub results here... if (get_latest_only and self.request_info.last_fetch_time != None): try: # Filter python objects with list comprehensions new_content = [x for x in result_content_json['Items'] if self.get_date_time(x['Timestamp']) > self.request_info.last_fetch_time] result_content_json['Items'] = new_content result['content'] = json.dumps(result_content_json) result['ok'] = True except ValueError as e: result['ok'] = False result['reason'] = str(e) except Exception as e: result['ok'] = False result['reason'] = 'Problem sorting results by date to get latest only. ' + str(e) result['available_matches'] = available_matches if 'Items' in result_content_json: result['returned_matches'] = len(result_content_json['Items']) else: result['returned_matches'] = 1 # Set last_fetch_time for next call if (get_latest_only): if (len(result_content_json['Items']) > 0): try: newlist = sorted(result_content_json['Items'], key=lambda k: self.get_date_time(k["Timestamp"]), reverse=True) most_recent = newlist[0]["Timestamp"] self.request_info.last_fetch_time = self.get_date_time(most_recent) except ValueError as e: result['ok'] = False result['reason'] = str(e) except Exception as e: result['ok'] = False result['reason'] = 'Problem sorting results by date to get latest only. ' + str(e) return result
python
def has_connection(graph, A, B): r"""Check if the given graph contains a path connecting A and B. Parameters ---------- graph : scipy.sparse matrix Adjacency matrix of the graph A : array_like The set of starting states B : array_like The set of end states Returns ------- hc : bool True if the graph contains a path connecting A and B, otherwise False. """ for istart in A: nodes = csgraph.breadth_first_order(graph, istart, directed=True, return_predecessors=False) if has_path(nodes, A, B): return True return False
java
private static StartupInfo parseArguments(String args[]) { InstanceId instance = InstanceId.NODEZERO; StartupOption startOpt = StartupOption.REGULAR; boolean isStandby= false; String serviceName = null; boolean force = false; int argsLen = (args == null) ? 0 : args.length; for (int i=0; i < argsLen; i++) { String cmd = args[i]; if (StartupOption.SERVICE.getName().equalsIgnoreCase(cmd)) { if (++i < argsLen) { serviceName = args[i]; } else { return null; } } else if (StartupOption.STANDBY.getName().equalsIgnoreCase(cmd)) { isStandby = true; } else if (StartupOption.NODEZERO.getName().equalsIgnoreCase(cmd)) { instance = InstanceId.NODEZERO; } else if (StartupOption.NODEONE.getName().equalsIgnoreCase(cmd)) { instance = InstanceId.NODEONE; } else if (StartupOption.FORMAT.getName().equalsIgnoreCase(cmd)) { startOpt = StartupOption.FORMAT; } else if (StartupOption.FORMATFORCE.getName().equalsIgnoreCase(cmd)) { startOpt = StartupOption.FORMATFORCE; } else if (StartupOption.REGULAR.getName().equalsIgnoreCase(cmd)) { startOpt = StartupOption.REGULAR; } else if (StartupOption.UPGRADE.getName().equalsIgnoreCase(cmd)) { startOpt = StartupOption.UPGRADE; } else if (StartupOption.ROLLBACK.getName().equalsIgnoreCase(cmd)) { startOpt = StartupOption.ROLLBACK; } else if (StartupOption.FINALIZE.getName().equalsIgnoreCase(cmd)) { startOpt = StartupOption.FINALIZE; } else if (StartupOption.IMPORT.getName().equalsIgnoreCase(cmd)) { startOpt = StartupOption.IMPORT; } else if (StartupOption.FORCE.getName().equalsIgnoreCase(cmd)) { force = true; } else { return null; } } return new StartupInfo(startOpt, instance, isStandby, serviceName, force); }
java
public static boolean annotationTypeMatches(Class<? extends Annotation> type, JavacNode node) { if (node.getKind() != Kind.ANNOTATION) return false; return typeMatches(type, node, ((JCAnnotation) node.get()).annotationType); }
python
def commit(self, message, files=None): """Run git-commit.""" if files: self.add(*files) return _run_command(["git", "commit", "-m", f'"{message}"'])
python
def credit_card_security_code(self, card_type=None): """ Returns a security code string. """ sec_len = self._credit_card_type(card_type).security_code_length return self.numerify('#' * sec_len)
python
def fix_jumps(self, row_selected, delta): '''fix up jumps when we add/remove rows''' numrows = self.grid_mission.GetNumberRows() for row in range(numrows): command = self.grid_mission.GetCellValue(row, ME_COMMAND_COL) if command in ["DO_JUMP", "DO_CONDITION_JUMP"]: p1 = int(float(self.grid_mission.GetCellValue(row, ME_P1_COL))) if p1 > row_selected and p1+delta>0: self.grid_mission.SetCellValue(row, ME_P1_COL, str(float(p1+delta)))
python
def convolve_map(m, k, cpix, threshold=0.001, imin=0, imax=None, wmap=None): """ Perform an energy-dependent convolution on a sequence of 2-D spatial maps. Parameters ---------- m : `~numpy.ndarray` 3-D map containing a sequence of 2-D spatial maps. First dimension should be energy. k : `~numpy.ndarray` 3-D map containing a sequence of convolution kernels (PSF) for each slice in m. This map should have the same dimension as m. cpix : list Indices of kernel reference pixel in the two spatial dimensions. threshold : float Kernel amplitude imin : int Minimum index in energy dimension. imax : int Maximum index in energy dimension. wmap : `~numpy.ndarray` 3-D map containing a sequence of 2-D spatial maps of weights. First dimension should be energy. This map should have the same dimension as m. """ islice = slice(imin, imax) o = np.zeros(m[islice, ...].shape) ix = int(cpix[0]) iy = int(cpix[1]) # Loop over energy for i in range(m[islice, ...].shape[0]): ks = k[islice, ...][i, ...] ms = m[islice, ...][i, ...] mx = ks[ix, :] > ks[ix, iy] * threshold my = ks[:, iy] > ks[ix, iy] * threshold nx = int(max(3, np.round(np.sum(mx) / 2.))) ny = int(max(3, np.round(np.sum(my) / 2.))) # Ensure that there is an odd number of pixels in the kernel # array if ix + nx + 1 >= ms.shape[0] or ix - nx < 0: nx -= 1 ny -= 1 sx = slice(ix - nx, ix + nx + 1) sy = slice(iy - ny, iy + ny + 1) ks = ks[sx, sy] # origin = [0, 0] # if ks.shape[0] % 2 == 0: origin[0] += 1 # if ks.shape[1] % 2 == 0: origin[1] += 1 # o[i,...] = ndimage.convolve(ms, ks, mode='constant', # origin=origin, cval=0.0) o[i, ...] = scipy.signal.fftconvolve(ms, ks, mode='same') if wmap is not None: o[i, ...] *= wmap[islice, ...][i, ...] return o
python
def recruitment(temporalcommunities, staticcommunities): """ Calculates recruitment coefficient for each node. Recruitment coefficient is the average probability of nodes from the same static communities being in the same temporal communities at other time-points or during different tasks. Parameters: ------------ temporalcommunities : array temporal communities vector (node,time) staticcommunities : array Static communities vector for each node Returns: ------- Rcoeff : array recruitment coefficient for each node References: ----------- Danielle S. Bassett, Muzhi Yang, Nicholas F. Wymbs, Scott T. Grafton. Learning-Induced Autonomy of Sensorimotor Systems. Nat Neurosci. 2015 May;18(5):744-51. Marcelo Mattar, Michael W. Cole, Sharon Thompson-Schill, Danielle S. Bassett. A Functional Cartography of Cognitive Systems. PLoS Comput Biol. 2015 Dec 2;11(12):e1004533. """ # make sure the static and temporal communities have the same number of nodes if staticcommunities.shape[0] != temporalcommunities.shape[0]: raise ValueError( 'Temporal and static communities have different dimensions') alleg = allegiance(temporalcommunities) Rcoeff = np.zeros(len(staticcommunities)) for i, statcom in enumerate(staticcommunities): Rcoeff[i] = np.mean(alleg[i, staticcommunities == statcom]) return Rcoeff
python
def _enum_from_op_string(op_string): """Convert a string representation of a binary operator to an enum. These enums come from the protobuf message definition ``StructuredQuery.FieldFilter.Operator``. Args: op_string (str): A comparison operation in the form of a string. Acceptable values are ``<``, ``<=``, ``==``, ``>=`` and ``>``. Returns: int: The enum corresponding to ``op_string``. Raises: ValueError: If ``op_string`` is not a valid operator. """ try: return _COMPARISON_OPERATORS[op_string] except KeyError: choices = ", ".join(sorted(_COMPARISON_OPERATORS.keys())) msg = _BAD_OP_STRING.format(op_string, choices) raise ValueError(msg)
python
def variable_name_from_full_name(full_name): """Extract the variable name from a full resource name. >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/var-name') "var-name" >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/another/var/name') "another/var/name" :type full_name: str :param full_name: The full resource name of a variable. The full resource name looks like ``projects/prj-name/configs/cfg-name/variables/var-name`` and is returned as the ``name`` field of a variable resource. See https://cloud.google.com/deployment-manager/runtime-configurator/reference/rest/v1beta1/projects.configs.variables :rtype: str :returns: The variable's short name, given its full resource name. :raises: :class:`ValueError` if ``full_name`` is not the expected format """ projects, _, configs, _, variables, result = full_name.split("/", 5) if projects != "projects" or configs != "configs" or variables != "variables": raise ValueError( "Unexpected format of resource", full_name, 'Expected "projects/{proj}/configs/{cfg}/variables/..."', ) return result
java
public String getStringValue(String property) { final List<JawrConfigManagerMBean> mBeans = getInitializedConfigurationManagers(); try { if (mBeans.size() == 3) { if (areEquals(getProperty(jsMBean, property), getProperty(cssMBean, property), getProperty(binaryMBean, property))) { return getProperty(jsMBean, property); } else { return NOT_IDENTICAL_VALUES; } } if (mBeans.size() == 2) { JawrConfigManagerMBean mBean1 = mBeans.get(0); JawrConfigManagerMBean mBean2 = mBeans.get(1); if (areEquals(getProperty(mBean1, property), getProperty(mBean2, property))) { return getProperty(mBean1, property); } else { return NOT_IDENTICAL_VALUES; } } JawrConfigManagerMBean mBean1 = mBeans.get(0); return getProperty(mBean1, property); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { return ERROR_VALUE; } }
java
public String buildCheckboxEnableNotification() { String propVal = null; if (!isMultiOperation()) { // get current settings for single resource dialog try { propVal = getCms().readPropertyObject( getParamResource(), CmsPropertyDefinition.PROPERTY_ENABLE_NOTIFICATION, false).getValue(); } catch (CmsException e) { if (LOG.isInfoEnabled()) { LOG.info(e.getLocalizedMessage()); } } } if (CmsStringUtil.isEmpty(propVal)) { propVal = CmsStringUtil.FALSE; } StringBuffer result = new StringBuffer(512); result.append("<input type=\"checkbox\" style=\"text-align:left\" name=\""); result.append(PARAM_ENABLE_NOTIFICATION); if (Boolean.valueOf(propVal).booleanValue()) { result.append("\" checked=\"checked"); } result.append("\" value=\"true\">"); return result.toString(); }
java
private T checkHealthyAndRetry(T resource, long endTimeMs) throws TimeoutException, IOException { if (isHealthy(resource)) { return resource; } else { LOG.info("Clearing unhealthy resource {}.", resource); remove(resource); closeResource(resource); return acquire(endTimeMs - mClock.millis(), TimeUnit.MILLISECONDS); } }
python
def header_encode_lines(self, string, maxlengths): """Header-encode a string by converting it first to bytes. This is similar to `header_encode()` except that the string is fit into maximum line lengths as given by the argument. :param string: A unicode string for the header. It must be possible to encode this string to bytes using the character set's output codec. :param maxlengths: Maximum line length iterator. Each element returned from this iterator will provide the next maximum line length. This parameter is used as an argument to built-in next() and should never be exhausted. The maximum line lengths should not count the RFC 2047 chrome. These line lengths are only a hint; the splitter does the best it can. :return: Lines of encoded strings, each with RFC 2047 chrome. """ # See which encoding we should use. codec = self.output_codec or 'us-ascii' header_bytes = _encode(string, codec) encoder_module = self._get_encoder(header_bytes) encoder = partial(encoder_module.header_encode, charset=codec) # Calculate the number of characters that the RFC 2047 chrome will # contribute to each line. charset = self.get_output_charset() extra = len(charset) + RFC2047_CHROME_LEN # Now comes the hard part. We must encode bytes but we can't split on # bytes because some character sets are variable length and each # encoded word must stand on its own. So the problem is you have to # encode to bytes to figure out this word's length, but you must split # on characters. This causes two problems: first, we don't know how # many octets a specific substring of unicode characters will get # encoded to, and second, we don't know how many ASCII characters # those octets will get encoded to. Unless we try it. Which seems # inefficient. In the interest of being correct rather than fast (and # in the hope that there will be few encoded headers in any such # message), brute force it. :( lines = [] current_line = [] maxlen = next(maxlengths) - extra for character in string: current_line.append(character) this_line = EMPTYSTRING.join(current_line) length = encoder_module.header_length(_encode(this_line, charset)) if length > maxlen: # This last character doesn't fit so pop it off. current_line.pop() # Does nothing fit on the first line? if not lines and not current_line: lines.append(None) else: separator = (' ' if lines else '') joined_line = EMPTYSTRING.join(current_line) header_bytes = _encode(joined_line, codec) lines.append(encoder(header_bytes)) current_line = [character] maxlen = next(maxlengths) - extra joined_line = EMPTYSTRING.join(current_line) header_bytes = _encode(joined_line, codec) lines.append(encoder(header_bytes)) return lines
java
protected long loadAll( NodeSequence sequence, QueueBuffer<BufferedRow> buffer, AtomicLong batchSize ) { return loadAll(sequence, buffer, batchSize, null, 0); }
java
private DiffPart decodeCut(final int blockSize_S, final int blockSize_E, final int blockSize_B) throws DecodingException { if (blockSize_S < 1 || blockSize_E < 1 || blockSize_B < 1) { throw new DecodingException("Invalid value for blockSize_S: " + blockSize_S + ", blockSize_E: " + blockSize_E + " or blockSize_B: " + blockSize_B); } int s = r.read(blockSize_S); int e = r.read(blockSize_E); int b = r.read(blockSize_B); DiffPart part = new DiffPart(DiffAction.CUT); part.setStart(s); part.setLength(e); part.setText(Integer.toString(b)); r.skip(); return part; }
python
def find_processes_by_filename(self, fileName): """ @type fileName: str @param fileName: Filename to search for. If it's a full pathname, the match must be exact. If it's a base filename only, the file part is matched, regardless of the directory where it's located. @note: If the process is not found and the file extension is not given, this method will search again assuming a default extension (.exe). @rtype: list of tuple( L{Process}, str ) @return: List of processes matching the given main module filename. Each tuple contains a Process object and it's filename. """ found = self.__find_processes_by_filename(fileName) if not found: fn, ext = PathOperations.split_extension(fileName) if not ext: fileName = '%s.exe' % fn found = self.__find_processes_by_filename(fileName) return found
python
def fetch(self, **kwargs) -> 'FetchContextManager': ''' Sends the request to the server and reads the response. You may use this method either with plain synchronous Session or AsyncSession. Both the followings patterns are valid: .. code-block:: python3 from ai.backend.client.request import Request from ai.backend.client.session import Session with Session() as sess: rqst = Request(sess, 'GET', ...) with rqst.fetch() as resp: print(resp.text()) .. code-block:: python3 from ai.backend.client.request import Request from ai.backend.client.session import AsyncSession async with AsyncSession() as sess: rqst = Request(sess, 'GET', ...) async with rqst.fetch() as resp: print(await resp.text()) ''' assert self.method in self._allowed_methods, \ 'Disallowed HTTP method: {}'.format(self.method) self.date = datetime.now(tzutc()) self.headers['Date'] = self.date.isoformat() if self.content_type is not None: self.headers['Content-Type'] = self.content_type full_url = self._build_url() self._sign(full_url.relative()) rqst_ctx = self.session.aiohttp_session.request( self.method, str(full_url), data=self._pack_content(), timeout=_default_request_timeout, headers=self.headers) return FetchContextManager(self.session, rqst_ctx, **kwargs)
java
@Inject(optional = true) protected Pattern setEndTag(@Named(AbstractMultiLineCommentProvider.END_TAG) final String endTag) { return this.endTagPattern = Pattern.compile((endTag + "\\z")); }
python
def _purge_expired(self): """ Remove all expired entries from the cache that do not have a reference count. """ time_horizon = time.time() - self._keep_time new_cache = {} dec_count_for = [] for (k, v) in self._cache.items(): if v.count > 0: if k not in self._block_store: new_cache[k] = v else: if v.timestamp > time_horizon: new_cache[k] = v else: block = v.value if block is not None: dec_count_for.append(block.previous_block_id) elif v.timestamp > time_horizon: new_cache[k] = v else: block = v.value # Handle NULL_BLOCK_IDENTIFIER if block is not None: dec_count_for.append(block.previous_block_id) self._cache = new_cache for block_id in dec_count_for: if block_id in self._cache: self._cache[block_id].dec_count()
python
def postings(self, quarter, stats_counter=None): """Yield job postings in common schema format Args: quarter (str) The quarter, in format '2015Q1' stats_counter (object, optional) A counter that can track both input and output documents using a 'track' method. """ logging.info('Finding postings for %s', quarter) for posting in self._iter_postings(quarter): transformed = self._transform(posting) transformed['id'] = '{}_{}'.format( self.partner_id, self._id(posting) ) if stats_counter: stats_counter.track( input_document=posting, output_document=transformed ) yield transformed
python
def nacm_enable_nacm(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") nacm = ET.SubElement(config, "nacm", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-acm") enable_nacm = ET.SubElement(nacm, "enable-nacm") enable_nacm.text = kwargs.pop('enable_nacm') callback = kwargs.pop('callback', self._callback) return callback(config)
python
def check_arguments(self): """Make sure all arguments have a specification""" for name, default in self.argdict.items(): if name not in self.names and default is NODEFAULT: raise NameError('Missing argparse specification for %r' % name)
python
def __load_profile(self, profile, uuid, verbose): """Create a new profile when the unique identity does not have any.""" def is_empty_profile(prf): return not (prf.name or prf.email or prf.gender or prf.gender_acc or prf.is_bot or prf.country_code) uid = api.unique_identities(self.db, uuid)[0] if profile: self.__create_profile(profile, uuid, verbose) elif is_empty_profile(uid.profile): self.__create_profile_from_identities(uid.identities, uuid, verbose) else: self.log("-- empty profile given for %s. Not updated" % uuid, verbose)
python
def getRegistrationReferralCounts(startDate,endDate): ''' When a user accesses the class registration page through a referral URL, the marketing_id gets saved in the extra JSON data associated with that registration. This just returns counts associated with how often given referral terms appear in a specified time window (i.e. how many people signed up by clicking through a referral button). ''' timeFilters = {} if startDate: timeFilters['dateTime__gte'] = startDate if endDate: timeFilters['dateTime__lt'] = endDate regs = Registration.objects.filter(**timeFilters) counter = Counter([x.data.get('marketing_id',None) for x in regs if isinstance(x.data,dict)] + [None for x in regs if not isinstance(x.data,dict)]) results = [{'code': k or _('None'), 'count': v} for k,v in counter.items()] return results
java
@Override public void startElement(String namespaceURI, String sName, String qName, Attributes attrs) throws SAXException { if (isParsing || qName.equals(currentRoot)) { isParsing = true; currentNode = new XMLNode(currentNode, qName); for (int i = 0; i < attrs.getLength(); i++) currentNode.attrs.put(attrs.getLocalName(i), attrs.getValue(i)); if (qName.equals(currentRoot)) xmlElementsMap.put(qName, currentNode); } }
python
def prepend(self, key, val, time=0, min_compress_len=0): '''Prepend the value to the beginning of the existing key's value. Only stores in memcache if key already exists. Also see L{append}. @return: Nonzero on success. @rtype: int ''' return self._set("prepend", key, val, time, min_compress_len)
java
@Override public int compareTo(Days otherAmount) { int thisValue = this.days; int otherValue = otherAmount.days; return Integer.compare(thisValue, otherValue); }
python
def main(): """Command-Mode: Retrieve and display data then process commands.""" (cred, providers) = config_read() cmd_mode = True conn_objs = cld.get_conns(cred, providers) while cmd_mode: nodes = cld.get_data(conn_objs, providers) node_dict = make_node_dict(nodes, "name") idx_tbl = table.indx_table(node_dict, True) cmd_mode = ui.ui_main(idx_tbl, node_dict) print("\033[?25h")
java
public Future<?> scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit) { Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed"); ScheduledFuture<?> scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(task, initialDelay, delay, unit); return new InternalScheduledFutureTask(scheduledFuture); }
java
private ExpressionAndSubstitution convertIntoExpressionAndSubstitution(ImmutableExpression expression, ImmutableSet<Variable> nonLiftableVariables) throws UnsatisfiableConditionException { ImmutableSet<ImmutableExpression> expressions = expression.flattenAND(); ImmutableSet<ImmutableExpression> functionFreeEqualities = expressions.stream() .filter(e -> e.getFunctionSymbol().equals(EQ)) .filter(e -> { ImmutableList<? extends ImmutableTerm> arguments = e.getTerms(); return arguments.stream().allMatch(t -> t instanceof NonFunctionalTerm); }) .collect(ImmutableCollectors.toSet()); ImmutableSubstitution<NonFunctionalTerm> normalizedUnifier = unify(functionFreeEqualities.stream() .map(ImmutableFunctionalTerm::getTerms) .map(args -> Maps.immutableEntry( (NonFunctionalTerm) args.get(0), (NonFunctionalTerm)args.get(1))), nonLiftableVariables); Optional<ImmutableExpression> newExpression = immutabilityTools.foldBooleanExpressions( Stream.concat( // Expressions that are not function-free equalities expressions.stream() .filter(e -> !functionFreeEqualities.contains(e)) .map(normalizedUnifier::applyToBooleanExpression), // Equalities that must remain normalizedUnifier.getImmutableMap().entrySet().stream() .filter(e -> nonLiftableVariables.contains(e.getKey())) .map(e -> termFactory.getImmutableExpression(EQ, e.getKey(), e.getValue())) )); return new ExpressionAndSubstitution(newExpression, normalizedUnifier.reduceDomainToIntersectionWith( Sets.difference(normalizedUnifier.getDomain(), nonLiftableVariables).immutableCopy())); }
python
def rotate(self, pitch, roll, yaw): """ Rotate the gimbal to a specific vector. .. code-block:: python #Point the gimbal straight down vehicle.gimbal.rotate(-90, 0, 0) :param pitch: Gimbal pitch in degrees relative to the vehicle (see diagram for :ref:`attitude <figure_attitude>`). A value of 0 represents a camera pointed straight ahead relative to the front of the vehicle, while -90 points the camera straight down. :param roll: Gimbal roll in degrees relative to the vehicle (see diagram for :ref:`attitude <figure_attitude>`). :param yaw: Gimbal yaw in degrees relative to *global frame* (0 is North, 90 is West, 180 is South etc.) """ msg = self._vehicle.message_factory.mount_configure_encode( 0, 1, # target system, target component mavutil.mavlink.MAV_MOUNT_MODE_MAVLINK_TARGETING, #mount_mode 1, # stabilize roll 1, # stabilize pitch 1, # stabilize yaw ) self._vehicle.send_mavlink(msg) msg = self._vehicle.message_factory.mount_control_encode( 0, 1, # target system, target component pitch * 100, # pitch is in centidegrees roll * 100, # roll yaw * 100, # yaw is in centidegrees 0 # save position ) self._vehicle.send_mavlink(msg)
java
public static void notNull(Object parameter, String name, Object... args) throws IllegalArgumentException { if (parameter == null) { throw new IllegalArgumentException(String.format(name, args) + " parameter is null."); } }
java
private byte[] xor(final byte[] input) { final byte[] output = new byte[input.length]; if (this.secret.length == 0) { System.arraycopy(input, 0, output, 0, input.length); } else { int spos = 0; for (int pos = 0; pos < input.length; ++pos) { output[pos] = (byte) (input[pos] ^ this.secret[spos]); ++spos; if (spos >= this.secret.length) { spos = 0; } } } return output; }
java
@Override public String getServletPath() { // unwrap the request to prevent multiple unneeded attempts to generate missing JSP files // m_controller.getTopRequest() does not return the right request here when forwarding // this method is generally called exactly once per request on different servlet containers // only resin calls it twice ServletRequest req = getRequest(); while (req instanceof CmsFlexRequest) { req = ((CmsFlexRequest)req).getRequest(); } String servletPath = null; if (req instanceof HttpServletRequest) { servletPath = ((HttpServletRequest)req).getServletPath(); } else { servletPath = super.getServletPath(); } // generate missing JSP file CmsJspLoader jspLoader = getJspLoader(); if (jspLoader != null) { jspLoader.updateJspFromRequest(servletPath, this); } return servletPath; }
python
def check_yaml_configs(configs, key): """Get a diagnostic for the yaml *configs*. *key* is the section to look for to get a name for the config at hand. """ diagnostic = {} for i in configs: for fname in i: with open(fname) as stream: try: res = yaml.load(stream, Loader=UnsafeLoader) msg = 'ok' except yaml.YAMLError as err: stream.seek(0) res = yaml.load(stream, Loader=BaseLoader) if err.context == 'while constructing a Python object': msg = err.problem else: msg = 'error' finally: try: diagnostic[res[key]['name']] = msg except (KeyError, TypeError): # this object doesn't have a 'name' pass return diagnostic
java
public static long castToIntegral(Decimal dec) { BigDecimal bd = dec.toBigDecimal(); // rounding down. This is consistent with float=>int, // and consistent with SQLServer, Spark. bd = bd.setScale(0, RoundingMode.DOWN); return bd.longValue(); }
python
def getPixelValue(self, x, y): """Get the value of a pixel from the data, handling voids in the SRTM data.""" assert x < self.size, "x: %d<%d" % (x, self.size) assert y < self.size, "y: %d<%d" % (y, self.size) # Same as calcOffset, inlined for performance reasons offset = x + self.size * (self.size - y - 1) #print offset value = self.data[offset] if value == -32768: return -1 # -32768 is a special value for areas with no data return value
python
def __substituteFromClientStatement(self,match,prevResponse,extraSymbol="",sessionID = "general"): """ Substitute from Client statement into respose """ prev = 0 startPadding = 1+len(extraSymbol) finalResponse = "" for m in re.finditer(r'%'+extraSymbol+'[0-9]+', prevResponse): start = m.start(0) end = m.end(0) num = int(prevResponse[start+startPadding:end]) finalResponse += prevResponse[prev:start] try:finalResponse += self._quote(self._substitute(match.group(num)),sessionID) except IndexError as e:pass prev = end namedGroup = match.groupdict() if namedGroup: prevResponse = finalResponse + prevResponse[prev:] finalResponse = "" prev = 0 for m in re.finditer(r'%'+extraSymbol+'([a-zA-Z_][a-zA-Z_0-9]*)([^a-zA-Z_0-9]|$)', prevResponse): start = m.start(1) end = m.end(1) finalResponse += prevResponse[prev:start] try: value = namedGroup[prevResponse[start+startPadding:end]] if value:finalResponse += self._quote(self._substitute(value),sessionID) except KeyError as e:pass prev = end return finalResponse + prevResponse[prev:]
java
@Override protected void initParser() throws MtasConfigException { super.initParser(); if (config != null) { // always word, no mappings wordType = new MtasParserType<>(MAPPING_TYPE_WORD, null, false); for (int i = 0; i < config.children.size(); i++) { MtasConfiguration current = config.children.get(i); if (current.name.equals("mappings")) { for (int j = 0; j < current.children.size(); j++) { if (current.children.get(j).name.equals("mapping")) { MtasConfiguration mapping = current.children.get(j); String typeMapping = mapping.attributes.get("type"); String nameMapping = mapping.attributes.get("name"); if ((typeMapping != null)) { if (typeMapping.equals(MAPPING_TYPE_WORD)) { MtasSketchParserMappingWord m = new MtasSketchParserMappingWord(); m.processConfig(mapping); wordType.addItem(m); } else if (typeMapping.equals(MAPPING_TYPE_WORD_ANNOTATION) && (nameMapping != null)) { MtasSketchParserMappingWordAnnotation m = new MtasSketchParserMappingWordAnnotation(); m.processConfig(mapping); if (wordAnnotationTypes .containsKey(Integer.parseInt(nameMapping))) { wordAnnotationTypes.get(Integer.parseInt(nameMapping)) .addItem(m); } else { MtasParserType<MtasParserMapping<?>> t = new MtasParserType<>( typeMapping, nameMapping, false); t.addItem(m); wordAnnotationTypes.put(Integer.parseInt(nameMapping), t); } } else if (typeMapping.equals(MAPPING_TYPE_GROUP) && (nameMapping != null)) { MtasSketchParserMappingGroup m = new MtasSketchParserMappingGroup(); m.processConfig(mapping); if (groupTypes.containsKey(nameMapping)) { groupTypes.get(nameMapping).addItem(m); } else { MtasParserType<MtasParserMapping<?>> t = new MtasParserType<>( typeMapping, nameMapping, false); t.addItem(m); groupTypes.put(nameMapping, t); } } else { throw new MtasConfigException("unknown mapping type " + typeMapping + " or missing name"); } } } } } } } }
python
def add_reference_context_args(parser): """ Extends an ArgumentParser instance with the following commandline arguments: --context-size """ reference_context_group = parser.add_argument_group("Reference Transcripts") parser.add_argument( "--context-size", default=CDNA_CONTEXT_SIZE, type=int) return reference_context_group
java
public static Basic2DMatrix constant(int rows, int columns, double constant) { double[][] array = new double[rows][columns]; for (int i = 0; i < rows; i++) { Arrays.fill(array[i], constant); } return new Basic2DMatrix(array); }
python
def rogers_huff_r(gn): """Estimate the linkage disequilibrium parameter *r* for each pair of variants using the method of Rogers and Huff (2008). Parameters ---------- gn : array_like, int8, shape (n_variants, n_samples) Diploid genotypes at biallelic variants, coded as the number of alternate alleles per call (i.e., 0 = hom ref, 1 = het, 2 = hom alt). Returns ------- r : ndarray, float, shape (n_variants * (n_variants - 1) // 2,) Matrix in condensed form. Examples -------- >>> import allel >>> g = allel.GenotypeArray([[[0, 0], [1, 1], [0, 0]], ... [[0, 0], [1, 1], [0, 0]], ... [[1, 1], [0, 0], [1, 1]], ... [[0, 0], [0, 1], [-1, -1]]], dtype='i1') >>> gn = g.to_n_alt(fill=-1) >>> gn array([[ 0, 2, 0], [ 0, 2, 0], [ 2, 0, 2], [ 0, 1, -1]], dtype=int8) >>> r = allel.rogers_huff_r(gn) >>> r # doctest: +ELLIPSIS array([ 1. , -1.0000001, 1. , -1.0000001, 1. , -1. ], dtype=float32) >>> r ** 2 # doctest: +ELLIPSIS array([1. , 1.0000002, 1. , 1.0000002, 1. , 1. ], dtype=float32) >>> from scipy.spatial.distance import squareform >>> squareform(r ** 2) array([[0. , 1. , 1.0000002, 1. ], [1. , 0. , 1.0000002, 1. ], [1.0000002, 1.0000002, 0. , 1. ], [1. , 1. , 1. , 0. ]], dtype=float32) """ # check inputs gn = asarray_ndim(gn, 2, dtype='i1') gn = memoryview_safe(gn) # compute correlation coefficients r = gn_pairwise_corrcoef_int8(gn) # convenience for singletons if r.size == 1: r = r[0] return r
java
public MarkedSection addMarkedSection() { MarkedSection section = new MarkedSection(new Section(null, numberDepth + 1)); add(section); return section; }
java
private static synchronized FileOutputWriter createFileWriter(final TypeDefinition type, final DecompilerSettings settings) throws IOException { final String outputDirectory = settings.getOutputDirectory(); final String fileName = type.getName() + settings.getLanguage().getFileExtension(); final String packageName = type.getPackageName(); // foo.Bar -> foo/Bar.java final String subDir = StringUtils.defaultIfEmpty(packageName, "").replace('.', File.separatorChar); final String outputPath = PathHelper.combine(outputDirectory, subDir, fileName); final File outputFile = new File(outputPath); final File parentDir = outputFile.getParentFile(); if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs()) { throw new IllegalStateException("Could not create directory:" + parentDir); } if (!outputFile.exists() && !outputFile.createNewFile()) { throw new IllegalStateException("Could not create output file: " + outputPath); } return new FileOutputWriter(outputFile, settings); }
java
@VisibleForTesting protected static Dimension getMaxLabelSize(final ScaleBarRenderSettings settings) { float maxLabelHeight = 0.0f; float maxLabelWidth = 0.0f; for (final Label label: settings.getLabels()) { maxLabelHeight = Math.max(maxLabelHeight, label.getHeight()); maxLabelWidth = Math.max(maxLabelWidth, label.getWidth()); } return new Dimension((int) Math.ceil(maxLabelWidth), (int) Math.ceil(maxLabelHeight)); }
java
public static void eachByte(Path self, int bufferLen, @ClosureParams(value = FromString.class, options = "byte[],Integer") Closure closure) throws IOException { BufferedInputStream is = newInputStream(self); IOGroovyMethods.eachByte(is, bufferLen, closure); }
java
public void setActionNames(java.util.Collection<String> actionNames) { if (actionNames == null) { this.actionNames = null; return; } this.actionNames = new com.amazonaws.internal.SdkInternalList<String>(actionNames); }
java
public JType []getActualTypeArguments() { Type []rawArgs = _type.getActualTypeArguments(); JType []args = new JType[rawArgs.length]; for (int i = 0; i < args.length; i++) { Type type = rawArgs[i]; if (type instanceof Class) { args[i] = _loader.forName(((Class) type).getName()); } else if (type instanceof ParameterizedType) args[i] = new JTypeWrapper(_loader, (ParameterizedType) type); else { args[i] = _loader.forName("java.lang.Object"); // jpa/0gg0 // throw new IllegalStateException(type.toString()); } } return args; }
python
def import_element(self, xml_element): """ Imports the element from an lxml element and loads its content. """ super(HTMLElement, self).import_element(xml_element) self.content = self.get_html_content()
python
def backward(ctx, grad_output): """ In the backward pass, we set the gradient to 1 for the winning units, and 0 for the others. """ batchSize = grad_output.shape[0] indices, = ctx.saved_tensors g = grad_output.reshape((batchSize, -1)) grad_x = torch.zeros_like(g, requires_grad=False) grad_x.scatter_(1, indices, g.gather(1, indices)) grad_x = grad_x.reshape(grad_output.shape) return grad_x, None, None, None
java
private String toDN(String username) { String userDN = new StringBuilder(userDnPrefix).append(username).append(this.userDnSuffix).toString(); return userDN; }
java
public void debug(Object message, Throwable t) { doLog(Level.DEBUG, FQCN, message, null, t); }
java
public List<String> getDirectoryEntries(VirtualFile mountPoint, VirtualFile target) { final String[] names = getFile(mountPoint, target).list(); return names == null ? Collections.<String>emptyList() : Arrays.asList(names); }
python
def get_instance(self, payload): """ Build an instance of SyncListInstance :param dict payload: Payload response from the API :returns: twilio.rest.sync.v1.service.sync_list.SyncListInstance :rtype: twilio.rest.sync.v1.service.sync_list.SyncListInstance """ return SyncListInstance(self._version, payload, service_sid=self._solution['service_sid'], )
python
def position_with_ref(msg, lat_ref, lon_ref): """Decode position with only one message, knowing reference nearby location, such as previously calculated location, ground station, or airport location, etc. Works with both airborne and surface position messages. The reference position shall be with in 180NM (airborne) or 45NM (surface) of the true position. Args: msg (string): even message (28 bytes hexadecimal string) lat_ref: previous known latitude lon_ref: previous known longitude Returns: (float, float): (latitude, longitude) of the aircraft """ tc = typecode(msg) if 5<=tc<=8: return surface_position_with_ref(msg, lat_ref, lon_ref) elif 9<=tc<=18 or 20<=tc<=22: return airborne_position_with_ref(msg, lat_ref, lon_ref) else: raise RuntimeError("incorrect or inconsistant message types")
python
def convert_decimal(value, parameter): ''' Converts to decimal.Decimal: '', '-', None convert to parameter default Anything else uses Decimal constructor ''' value = _check_default(value, parameter, ( '', '-', None )) if value is None or isinstance(value, decimal.Decimal): return value try: return decimal.Decimal(value) except Exception as e: raise ValueError(str(e))
java
@SneakyThrows public static String dumps(@NonNull Map<String, ?> map) { Resource strResource = new StringResource(); try (JsonWriter writer = new JsonWriter(strResource)) { writer.beginDocument(); for (Map.Entry<String, ?> entry : map.entrySet()) { writer.property(entry.getKey(), entry.getValue()); } writer.endDocument(); } return strResource.readToString().trim(); }