language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@SuppressWarnings("deprecation") protected String getExpressionUrl(String expression) { String template = _config.getValue(Property.AUDIT_METRIC_URL_TEMPLATE.getName(), Property.AUDIT_METRIC_URL_TEMPLATE.getDefaultValue()); try { expression = URLEncoder.encode(expression, "UTF-8"); } catch (Exception ex) { expression = URLEncoder.encode(expression); } return template.replaceAll("\\$expression\\$", expression); }
python
def equals(self, other): ''' Structural equality of models. Args: other (HasProps) : the other instance to compare to Returns: True, if properties are structurally equal, otherwise False ''' # NOTE: don't try to use this to implement __eq__. Because then # you will be tempted to implement __hash__, which would interfere # with mutability of models. However, not implementing __hash__ # will make bokeh unusable in Python 3, where proper implementation # of __hash__ is required when implementing __eq__. if not isinstance(other, self.__class__): return False else: return self.properties_with_values() == other.properties_with_values()
java
@SuppressWarnings("unused") private void initalizeReferences(Collection<Bean> beans) { Map<BeanId, Bean> userProvided = BeanUtils.uniqueIndex(beans); for (Bean bean : beans) { for (String name : bean.getReferenceNames()) { List<BeanId> values = bean.getReference(name); if (values == null) { continue; } for (BeanId beanId : values) { // the does not exist in storage, but may exist in the // set of beans provided by the user. Bean ref = userProvided.get(beanId); if (ref == null) { Optional<Bean> optional = beanManager.getEager(beanId); if (optional.isPresent()) { ref = optional.get(); } } beanId.setBean(ref); schemaManager.setSchema(Arrays.asList(beanId.getBean())); } } } }
python
def block_view(self, mri): # type: (str) -> Block """Get a Block view from a Controller with given mri""" controller = self.get_controller(mri) block = controller.block_view() return block
python
def install_certs(ssl_dir, certs, chain=None, user='root', group='root'): """Install the certs passed into the ssl dir and append the chain if provided. :param ssl_dir: str Directory to create symlinks in :param certs: {} {'cn': {'cert': 'CERT', 'key': 'KEY'}} :param chain: str Chain to be appended to certs :param user: (Optional) Owner of certificate files. Defaults to 'root' :type user: str :param group: (Optional) Group of certificate files. Defaults to 'root' :type group: str """ for cn, bundle in certs.items(): cert_filename = 'cert_{}'.format(cn) key_filename = 'key_{}'.format(cn) cert_data = bundle['cert'] if chain: # Append chain file so that clients that trust the root CA will # trust certs signed by an intermediate in the chain cert_data = cert_data + os.linesep + chain write_file( path=os.path.join(ssl_dir, cert_filename), owner=user, group=group, content=cert_data, perms=0o640) write_file( path=os.path.join(ssl_dir, key_filename), owner=user, group=group, content=bundle['key'], perms=0o640)
python
def root_item_selected(self, item): """Root item has been selected: expanding it and collapsing others""" if self.show_all_files: return for root_item in self.get_top_level_items(): if root_item is item: self.expandItem(root_item) else: self.collapseItem(root_item)
python
def get_killer(args): """Returns a KillerBase instance subclassed based on the OS.""" if POSIX: log.debug('Platform: POSIX') from killer.killer_posix import KillerPosix return KillerPosix(config_path=args.config, debug=args.debug) elif WINDOWS: log.debug('Platform: Windows') from killer.killer_windows import KillerWindows return KillerWindows(config_path=args.config, debug=args.debug) else: # TODO: WSL # TODO: OSX # TODO: BSD raise NotImplementedError("Your platform is not currently supported." "If you would like support to be added, or " "if your platform is supported and this is " "a bug, please open an issue on GitHub!")
java
public void marshall(SetVaultNotificationsRequest setVaultNotificationsRequest, ProtocolMarshaller protocolMarshaller) { if (setVaultNotificationsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(setVaultNotificationsRequest.getAccountId(), ACCOUNTID_BINDING); protocolMarshaller.marshall(setVaultNotificationsRequest.getVaultName(), VAULTNAME_BINDING); protocolMarshaller.marshall(setVaultNotificationsRequest.getVaultNotificationConfig(), VAULTNOTIFICATIONCONFIG_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
public static <T extends Comparable<T>> T lt(T value) { reportMatcher(new LessThan<T>(value)); return null; }
java
private Locale getLocale(String acceptLanguage) { if (acceptLanguage == null) { acceptLanguage = "fr"; } String[] langs = acceptLanguage.split(","); return Locale.forLanguageTag(langs[0].split("-")[0]); }
python
def get_name_record(self, name, include_expired=False, include_history=False): """ Get the whois-related info for a name (not a subdomain). Optionally include the history. Return {'status': True, 'record': rec} on success Return {'error': ...} on error """ if not check_name(name): return {'error': 'invalid name', 'http_status': 400} name = str(name) db = get_db_state(self.working_dir) name_record = db.get_name(str(name), include_expired=include_expired, include_history=include_history) if name_record is None: db.close() return {"error": "Not found.", 'http_status': 404} else: assert 'opcode' in name_record, 'BUG: missing opcode in {}'.format(json.dumps(name_record, sort_keys=True)) name_record = self.load_name_info(db, name_record) db.close() # also get the subdomain resolver resolver = get_subdomain_resolver(name) name_record['resolver'] = resolver return {'status': True, 'record': name_record}
java
public static boolean isInternationalPhoneNumber(String s) { if (isEmpty(s)) return defaultEmptyOK; String normalizedPhone = stripCharsInBag(s, phoneNumberDelimiters); return isPositiveInteger(normalizedPhone); }
python
def _format_playlist_line(self, lineNum, pad, station): """ format playlist line so that if fills self.maxX """ line = "{0}. {1}".format(str(lineNum + self.startPos + 1).rjust(pad), station[0]) f_data = ' [{0}, {1}]'.format(station[2], station[1]) if version_info < (3, 0): if len(line.decode('utf-8', 'replace')) + len(f_data.decode('utf-8', 'replace')) > self.bodyMaxX -2: """ this is too long, try to shorten it by removing file size """ f_data = ' [{0}]'.format(station[1]) if len(line.decode('utf-8', 'replace')) + len(f_data.decode('utf-8', 'replace')) > self.bodyMaxX - 2: """ still too long. start removing chars """ while len(line.decode('utf-8', 'replace')) + len(f_data.decode('utf-8', 'replace')) > self.bodyMaxX - 3: f_data = f_data[:-1] f_data += ']' """ if too short, pad f_data to the right """ if len(line.decode('utf-8', 'replace')) + len(f_data.decode('utf-8', 'replace')) < self.maxX - 2: while len(line.decode('utf-8', 'replace')) + len(f_data.decode('utf-8', 'replace')) < self.maxX - 2: line += ' ' else: if len(line) + len(f_data) > self.bodyMaxX -2: """ this is too long, try to shorten it by removing file size """ f_data = ' [{0}]'.format(station[1]) if len(line) + len(f_data) > self.bodyMaxX - 2: """ still too long. start removing chars """ while len(line) + len(f_data) > self.bodyMaxX - 3: f_data = f_data[:-1] f_data += ']' """ if too short, pad f_data to the right """ if len(line) + len(f_data) < self.maxX - 2: while len(line) + len(f_data) < self.maxX - 2: line += ' ' line += f_data return line
java
public Observable<Page<DenyAssignmentInner>> listForResourceNextAsync(final String nextPageLink) { return listForResourceNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<DenyAssignmentInner>>, Page<DenyAssignmentInner>>() { @Override public Page<DenyAssignmentInner> call(ServiceResponse<Page<DenyAssignmentInner>> response) { return response.body(); } }); }
python
def assign_floating_ip(self, ip_addr, droplet_id): """ Assigns a Floating IP to a Droplet. """ if self.api_version == 2: params = {'type': 'assign','droplet_id': droplet_id} json = self.request('/floating_ips/' + ip_addr + '/actions', params=params, method='POST') return json['action'] else: raise DoError(v2_api_required_str)
java
@Override public SparseTensor elementwiseProduct(Tensor other) { int[] dimensionNums = getDimensionNumbers(); int[] dimensionSizes = getDimensionSizes(); int[] otherDimensions = other.getDimensionNumbers(); int[] otherSizes = other.getDimensionSizes(); // Check that dimensionNums contains a superset of otherDimensions int myInd = 0, otherInd = 0; int myLength = dimensionNums.length; int otherLength = otherDimensions.length; while (myInd < myLength && otherInd < otherLength) { if (dimensionNums[myInd] < otherDimensions[otherInd]) { myInd++; } else if (dimensionNums[myInd] == otherDimensions[otherInd]) { Preconditions.checkArgument(dimensionSizes[myInd] == otherSizes[otherInd], "dimensionSizes[myInd]: %s\notherSizes[otherInd]: %s", dimensionSizes[myInd], otherSizes[otherInd]); myInd++; otherInd++; } else { // Not a superset. Preconditions.checkArgument(false, "Dimensions not a superset"); } } // There are three possible multiplication implementations: an extremely // fast one for the case when both sets of dimensions are exactly equal, // a pretty fast one for when the dimensions of other line up // against the leftmost dimensions of this, and another for all // other cases. Check which case applies, then use the // fastest possible algorithm. for (int i = 0; i < otherDimensions.length; i++) { if (otherDimensions[i] != dimensionNums[i]) { // Not left aligned. return elementwiseMultiplyNaive(this, other); } } if (otherDimensions.length == dimensionNums.length) { // Both tensors contain the exact same set of dimensions return elementwiseMultiplySparseDense(this, other); } else { // Dimensions of other are aligned with the leftmost dimensions // of this tensor. return elementwiseMultiplyLeftAligned(this, other); } }
python
def interpolate(self, lons, lats, zdata, order=1): """ Base class to handle nearest neighbour, linear, and cubic interpolation. Given a triangulation of a set of nodes on the unit sphere, along with data values at the nodes, this method interpolates (or extrapolates) the value at a given longitude and latitude. Parameters ---------- lons : float / array of floats, shape (l,) longitudinal coordinate(s) on the sphere lats : float / array of floats, shape (l,) latitudinal coordinate(s) on the sphere zdata : array of floats, shape (n,) value at each point in the triangulation must be the same size of the mesh order : int (default=1) order of the interpolatory function used 0 = nearest-neighbour 1 = linear 3 = cubic Returns ------- zi : float / array of floats, shape (l,) interpolated value(s) at (lons, lats) err : int / array of ints, shape (l,) whether interpolation (0), extrapolation (1) or error (other) """ shape = lons.shape lons, lats = self._check_integrity(lons, lats) if order not in [0,1,3]: raise ValueError("order must be 0, 1, or 3") if zdata.size != self.npoints: raise ValueError("data must be of size {}".format(self.npoints)) zdata = self._shuffle_field(zdata) zi, zierr, ierr = _stripack.interp_n(order, lats, lons,\ self._x, self._y, self._z, zdata,\ self.lst, self.lptr, self.lend) if ierr != 0: print('Warning some points may have errors - check error array\n'.format(ierr)) zi[zierr < 0] = np.nan return zi.reshape(shape), zierr.reshape(shape)
python
def extract_tokens(representation, separators=SEPARATOR_CHARACTERS): """Extracts durations tokens from a duration representation. Parses the string representation incrementaly and raises on first error met. :param representation: duration representation :type representation: string """ buff = "" elements = [] last_index = 0 last_token = None for index, c in enumerate(representation): # if separator character is found, push # the content of the buffer in the elements list if c in separators: if buff: # If the last found token is invalid, # raise and InvalidTokenError if not valid_token(buff): raise InvalidTokenError( "Duration representation {0} contains " "an invalid token: {1}".format(representation, buff) ) # If buffer content is a separator word, for example # "and", just ignore it if not buff.strip() in SEPARATOR_TOKENS: elements.append(buff) # Anyway, reset buffer and last token marker # to their zero value buff = "" last_token = None else: token = compute_char_token(c) if (token is not None and last_token is not None and token != last_token): elements.append(buff) buff = c else: buff += c last_token = token # push the content left in representation # in the elements list elements.append(buff) return list(zip(elements[::2], elements[1::2]))
java
public void setSnapshotIdentifierList(java.util.Collection<String> snapshotIdentifierList) { if (snapshotIdentifierList == null) { this.snapshotIdentifierList = null; return; } this.snapshotIdentifierList = new com.amazonaws.internal.SdkInternalList<String>(snapshotIdentifierList); }
python
def Barati_high(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_. .. math:: C_D = 8\times 10^{-6}\left[(Re/6530)^2 + \tanh(Re) - 8\ln(Re)/\ln(10)\right] - 0.4119\exp(-2.08\times10^{43}/[Re + Re^2]^4) -2.1344\exp(-\{[\ln(Re^2 + 10.7563)/\ln(10)]^2 + 9.9867\}/Re) +0.1357\exp(-[(Re/1620)^2 + 10370]/Re) - 8.5\times 10^{-3}\{2\ln[\tanh(\tanh(Re))]/\ln(10) - 2825.7162\}/Re + 2.4795 Parameters ---------- Re : float Reynolds number of the sphere, [-] Returns ------- Cd : float Drag coefficient [-] Notes ----- Range is Re <= 1E6 This model is the wider-range model the authors developed. At sufficiently low diameters or Re values, drag is no longer a phenomena. Examples -------- Maching example in [1]_, in a table of calculated values. >>> Barati_high(200.) 0.7730544082789523 References ---------- .. [1] Barati, Reza, Seyed Ali Akbar Salehi Neyshabouri, and Goodarz Ahmadi. "Development of Empirical Models with High Accuracy for Estimation of Drag Coefficient of Flow around a Smooth Sphere: An Evolutionary Approach." Powder Technology 257 (May 2014): 11-19. doi:10.1016/j.powtec.2014.02.045. ''' Cd = (8E-6*((Re/6530.)**2 + tanh(Re) - 8*log(Re)/log(10.)) - 0.4119*exp(-2.08E43/(Re+Re**2)**4) - 2.1344*exp(-((log(Re**2 + 10.7563)/log(10))**2 + 9.9867)/Re) + 0.1357*exp(-((Re/1620.)**2 + 10370.)/Re) - 8.5E-3*(2*log(tanh(tanh(Re)))/log(10) - 2825.7162)/Re + 2.4795) return Cd
java
private void zSetParentSelectedDate(LocalDate dateValue) { if (parentDatePicker != null) { parentDatePicker.setDate(dateValue); } if (parentCalendarPanel != null) { parentCalendarPanel.setSelectedDate(dateValue); } }
python
def parse_record(self, node): """ Parses <Record> @param node: Node containing the <Record> element @type node: xml.etree.Element """ if self.current_simulation == None: self.raise_error('<Record> must be only be used inside a ' + 'simulation specification') if 'quantity' in node.lattrib: quantity = node.lattrib['quantity'] else: self.raise_error('<Record> must specify a quantity.') scale = node.lattrib.get('scale', None) color = node.lattrib.get('color', None) id = node.lattrib.get('id', None) self.current_simulation.add_record(Record(quantity, scale, color, id))
java
@Override protected void introspectWrapperSpecificInfo(com.ibm.ws.rsadapter.FFDCLogger info) { info.append("Underlying Statement: " + AdapterUtil.toString(stmtImpl), stmtImpl); info.append("Statement properties have changed? " + haveStatementPropertiesChanged); info.append("Poolability hint: " + (poolabilityHint ? "POOLABLE" : "NOT POOLABLE")); }
python
async def on_raw_cap_list(self, params): """ Update active capabilities. """ self._capabilities = { capab: False for capab in self._capabilities } for capab in params[0].split(): capab, value = self._capability_normalize(capab) self._capabilities[capab] = value if value else True
java
public double viterbiDecode(Instance instance, int[] guessLabel) { final int[] allLabel = featureMap.allLabels(); final int bos = featureMap.bosTag(); final int sentenceLength = instance.tagArray.length; final int labelSize = allLabel.length; int[][] preMatrix = new int[sentenceLength][labelSize]; double[][] scoreMatrix = new double[2][labelSize]; for (int i = 0; i < sentenceLength; i++) { int _i = i & 1; int _i_1 = 1 - _i; int[] allFeature = instance.getFeatureAt(i); final int transitionFeatureIndex = allFeature.length - 1; if (0 == i) { allFeature[transitionFeatureIndex] = bos; for (int j = 0; j < allLabel.length; j++) { preMatrix[0][j] = j; double score = score(allFeature, j); scoreMatrix[0][j] = score; } } else { for (int curLabel = 0; curLabel < allLabel.length; curLabel++) { double maxScore = Integer.MIN_VALUE; for (int preLabel = 0; preLabel < allLabel.length; preLabel++) { allFeature[transitionFeatureIndex] = preLabel; double score = score(allFeature, curLabel); double curScore = scoreMatrix[_i_1][preLabel] + score; if (maxScore < curScore) { maxScore = curScore; preMatrix[i][curLabel] = preLabel; scoreMatrix[_i][curLabel] = maxScore; } } } } } int maxIndex = 0; double maxScore = scoreMatrix[(sentenceLength - 1) & 1][0]; for (int index = 1; index < allLabel.length; index++) { if (maxScore < scoreMatrix[(sentenceLength - 1) & 1][index]) { maxIndex = index; maxScore = scoreMatrix[(sentenceLength - 1) & 1][index]; } } for (int i = sentenceLength - 1; i >= 0; --i) { guessLabel[i] = allLabel[maxIndex]; maxIndex = preMatrix[i][maxIndex]; } return maxScore; }
java
public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case KEY: return isSetKey(); case COUNT: return isSetCount(); } throw new IllegalStateException(); }
java
public void run() { LOGGER.debug("begin scan for config file changes ..."); try { Date lastModified = new Date(_xmlConfigFile.lastModified()); if (_lastTimeRead == null || lastModified.after(_lastTimeRead)) { LOGGER.info("loading config file changes ..."); this.loadServiceConfigFile(); _lastTimeRead = new Date(); } } catch (ConfigurationException e) { e.printStackTrace(); LOGGER.error( "Error loading configuation file: ", e ); } LOGGER.debug("finish scan for config file changes"); }
java
public DataSetBuilder sequence(String column, double initial, double step) { return sequence(column, (Double) initial, x -> x + step); }
java
public void setCostAdjustment(com.google.api.ads.admanager.axis.v201811.CostAdjustment costAdjustment) { this.costAdjustment = costAdjustment; }
java
public double getLowerBound(final int numStdDev) { if (!isEstimationMode()) { return getRetainedEntries(); } return BinomialBoundsN.getLowerBound(getRetainedEntries(), getTheta(), numStdDev, isEmpty_); }
java
public Color scaleCopy(float value) { Color copy = new Color(r,g,b,a); copy.r *= value; copy.g *= value; copy.b *= value; copy.a *= value; return copy; }
python
def file_is_attached(self, url): '''return true if at least one book has file with the given url as attachment ''' body = self._get_search_field('_attachments.url', url) return self.es.count(index=self.index_name, body=body)['count'] > 0
python
def setup(channel, direction, initial=None, pull_up_down=None): """ You need to set up every channel you are using as an input or an output. :param channel: the channel based on the numbering system you have specified (:py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM` or :py:attr:`GPIO.SUNXI`). :param direction: whether to treat the GPIO pin as input or output (use only :py:attr:`GPIO.IN` or :py:attr:`GPIO.OUT`). :param initial: (optional) When supplied and setting up an output pin, resets the pin to the value given (can be :py:attr:`0` / :py:attr:`GPIO.LOW` / :py:attr:`False` or :py:attr:`1` / :py:attr:`GPIO.HIGH` / :py:attr:`True`). :param pull_up_down: (optional) When supplied and setting up an input pin, configures the pin to 3.3V (pull-up) or 0V (pull-down) depending on the value given (can be :py:attr:`GPIO.PUD_OFF` / :py:attr:`GPIO.PUD_UP` / :py:attr:`GPIO.PUD_DOWN`) To configure a channel as an input: .. code:: python GPIO.setup(channel, GPIO.IN) To set up a channel as an output: .. code:: python GPIO.setup(channel, GPIO.OUT) You can also specify an initial value for your output channel: .. code:: python GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH) **Setup more than one channel:** You can set up more than one channel per call. For example: .. code:: python chan_list = [11,12] # add as many channels as you want! # you can tuples instead i.e.: # chan_list = (11,12) GPIO.setup(chan_list, GPIO.OUT) """ if _mode is None: raise RuntimeError("Mode has not been set") if pull_up_down is not None: if _gpio_warnings: warnings.warn("Pull up/down setting are not (yet) fully supported, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.", stacklevel=2) if isinstance(channel, list): for ch in channel: setup(ch, direction, initial) else: if channel in _exports: raise RuntimeError("Channel {0} is already configured".format(channel)) pin = get_gpio_pin(_mode, channel) try: sysfs.export(pin) except (OSError, IOError) as e: if e.errno == 16: # Device or resource busy if _gpio_warnings: warnings.warn("Channel {0} is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.".format(channel), stacklevel=2) sysfs.unexport(pin) sysfs.export(pin) else: raise e sysfs.direction(pin, direction) _exports[channel] = direction if direction == OUT and initial is not None: sysfs.output(pin, initial)
python
def add_annotation_layer(self, annotation_file, layer_name): """ adds all markables from the given annotation layer to the discourse graph. """ assert os.path.isfile(annotation_file), \ "Annotation file doesn't exist: {}".format(annotation_file) tree = etree.parse(annotation_file) root = tree.getroot() default_layers = {self.ns, self.ns+':markable', self.ns+':'+layer_name} # avoids eml.org namespace handling for markable in root.iterchildren(): markable_node_id = markable.attrib['id'] markable_attribs = add_prefix(markable.attrib, self.ns+':') self.add_node(markable_node_id, layers=default_layers, attr_dict=markable_attribs, label=markable_node_id+':'+layer_name) for target_node_id in spanstring2tokens(self, markable.attrib['span']): # manually add to_node if it's not in the graph, yet # cf. issue #39 if target_node_id not in self: self.add_node(target_node_id, # adding 'mmax:layer_name' here could be # misleading (e.g. each token would be part # of the 'mmax:sentence' layer layers={self.ns, self.ns+':markable'}, label=target_node_id) self.add_edge(markable_node_id, target_node_id, layers=default_layers, edge_type=EdgeTypes.spanning_relation, label=self.ns+':'+layer_name) # this is a workaround for Chiarcos-style MMAX files if has_antecedent(markable): antecedent_pointer = markable.attrib['anaphor_antecedent'] # mmax2 supports weird double antecedents, # e.g. "markable_1000131;markable_1000132", cf. Issue #40 # # handling these double antecendents increases the number of # chains, cf. commit edc28abdc4fd36065e8bbf5900eeb4d1326db153 for antecedent in antecedent_pointer.split(';'): ante_split = antecedent.split(":") if len(ante_split) == 2: # mark group:markable_n or secmark:markable_n as such edge_label = '{}:antecedent'.format(ante_split[0]) else: edge_label = ':antecedent' # handles both 'markable_n' and 'layer:markable_n' antecedent_node_id = ante_split[-1] if len(ante_split) == 2: antecedent_layer = ante_split[0] default_layers.add('{0}:{1}'.format(self.ns, antecedent_layer)) # manually add antecedent node if it's not yet in the graph # cf. issue #39 if antecedent_node_id not in self: self.add_node(antecedent_node_id, layers=default_layers) self.add_edge(markable_node_id, antecedent_node_id, layers=default_layers, edge_type=EdgeTypes.pointing_relation, label=self.ns+edge_label)
java
public static CommerceOrderNote remove(long commerceOrderNoteId) throws com.liferay.commerce.exception.NoSuchOrderNoteException { return getPersistence().remove(commerceOrderNoteId); }
python
def _load_instance(self, instance_id): """ Return instance with the given id. For performance reasons, the instance ID is first searched for in the collection of VM instances started by ElastiCluster (`self._instances`), then in the list of all instances known to the cloud provider at the time of the last update (`self._cached_instances`), and finally the cloud provider is directly queried. :param str instance_id: instance identifier :return: py:class:`boto.ec2.instance.Reservation` - instance :raises: `InstanceError` is returned if the instance can't be found in the local cache or in the cloud. """ # if instance is known, return it if instance_id in self._instances: return self._instances[instance_id] # else, check (cached) list from provider if instance_id not in self._cached_instances: self._cached_instances = self._build_cached_instances() if instance_id in self._cached_instances: inst = self._cached_instances[instance_id] self._instances[instance_id] = inst return inst # If we reached this point, the instance was not found neither # in the caches nor on the website. raise InstanceNotFoundError( "Instance `{instance_id}` not found" .format(instance_id=instance_id))
java
public static LocalTime now(Clock clock) { Jdk8Methods.requireNonNull(clock, "clock"); // inline OffsetTime factory to avoid creating object and InstantProvider checks final Instant now = clock.instant(); // called once ZoneOffset offset = clock.getZone().getRules().getOffset(now); long secsOfDay = now.getEpochSecond() % SECONDS_PER_DAY; secsOfDay = (secsOfDay + offset.getTotalSeconds()) % SECONDS_PER_DAY; if (secsOfDay < 0) { secsOfDay += SECONDS_PER_DAY; } return LocalTime.ofSecondOfDay(secsOfDay, now.getNano()); }
python
def get_http_info(self, request): """ Determine how to retrieve actual data by using request.mimetype. """ if self.is_json_type(request.mimetype): retriever = self.get_json_data else: retriever = self.get_form_data return self.get_http_info_with_retriever(request, retriever)
java
public static <T> void forEach(T[] input,boolean[] inputSkip,T[] output ,int outPutIndex,ForEachController<T> controller) { for(int i=0;i<input.length;i++) { if(inputSkip[i]) { continue; } output[outPutIndex]=input[i];//输出当前位锁定值 ComputeStatus status=controller.onOutEvent(output, outPutIndex); if(status.isStop()) { return; } if(status.isSkip()) {//跳过下层循环 continue; } outPutIndex++; if(outPutIndex>=input.length) {//如果是最后一个则返回 break; } //解锁下一个 inputSkip[i]=true;//锁定当前位占用索引,其它位不可使用该索引 forEach(input, inputSkip, output, outPutIndex,controller); outPutIndex--;//回到当前 inputSkip[i]=false;//释放锁定 } }
python
def one_of(*args): "Verifies that only one of the arguments is not None" for i, arg in enumerate(args): if arg is not None: for argh in args[i+1:]: if argh is not None: raise OperationError("Too many parameters") else: return raise OperationError("Insufficient parameters")
python
def read(self, n=CHUNK_SIZE): """ Read up to `n` bytes from the file descriptor, wrapping the underlying :func:`os.read` call with :func:`io_op` to trap common disconnection conditions. :meth:`read` always behaves as if it is reading from a regular UNIX file; socket, pipe, and TTY disconnection errors are masked and result in a 0-sized read like a regular file. :returns: Bytes read, or the empty to string to indicate disconnection was detected. """ if self.closed: # Refuse to touch the handle after closed, it may have been reused # by another thread. TODO: synchronize read()/write()/close(). return b('') s, disconnected = io_op(os.read, self.fd, n) if disconnected: LOG.debug('%r.read(): disconnected: %s', self, disconnected) return b('') return s
java
public final void entryRuleXExpressionInClosure() throws RecognitionException { try { // InternalXbaseWithAnnotations.g:934:1: ( ruleXExpressionInClosure EOF ) // InternalXbaseWithAnnotations.g:935:1: ruleXExpressionInClosure EOF { if ( state.backtracking==0 ) { before(grammarAccess.getXExpressionInClosureRule()); } pushFollow(FOLLOW_1); ruleXExpressionInClosure(); state._fsp--; if (state.failed) return ; if ( state.backtracking==0 ) { after(grammarAccess.getXExpressionInClosureRule()); } match(input,EOF,FOLLOW_2); if (state.failed) return ; } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { } return ; }
java
private void execute() { for (Client client : clientMap.values()) { if (client != null && client instanceof Batcher) { // if no batch operation performed{may be running in // transaction?} if (((Batcher) client).getBatchSize() == 0 || ((Batcher) client).executeBatch() > 0) { flushJoinTableData(); } } } }
python
def comparison(self, username): """ Get a comparison of scores between the "base user" and ``username``. A Key-Value returned will consist of the following: .. code-block:: none { ANIME_ID: [BASE_USER_SCORE, OTHER_USER_SCORE], ... } Example: .. code-block:: none { 30831: [3, 8], 31240: [4, 7], 32901: [1, 5], ... } .. warning:: The JSON returned isn't valid JSON. The keys are stored as integers instead of the JSON standard of strings. You'll want to force the keys to strings if you'll be using the ids elsewhere. :param str username: The username to compare the base users' scores to :return: Key-value pairs as described above :rtype: dict """ # Check if there's actually a base user to compare scores with. if not self._base_user or not self._base_scores: raise Exception("No base user has been specified. Call the `init` " "function to retrieve a base users' scores") # Create a local, deep-copy of the scores for modification scores = copy.deepcopy(self._base_scores) user_list = endpoints.myanimelist(username) for anime in user_list: id = anime["id"] score = anime["score"] if id in scores: scores[id].append(score) # Force to list so no errors when deleting keys. for key in list(scores.keys()): if not len(scores[key]) == 2: del scores[key] return scores
java
protected void checkExistingRestore(SnapshotIdentifier snapshotIdentifier) { Iterator<String> currentSpaces = snapshotProvider.getSpaces(); while (currentSpaces.hasNext()) { String spaceId = currentSpaces.next(); if (spaceId.equals(snapshotIdentifier.getRestoreSpaceId())) { // This snapshot has already been restored String error = "A request to restore snapshot with ID " + snapshotIdentifier.getSnapshotId() + " has been made previously. The snapshot is " + "being restored to space: " + spaceId; throw new TaskException(error); } } }
python
def _set_map_fport(self, v, load=False): """ Setter method for map_fport, mapped from YANG variable /rbridge_id/ag/nport_menu/nport_interface/nport/map/map_fport (container) If this variable is read-only (config: false) in the source YANG file, then _set_map_fport is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_map_fport() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=map_fport.map_fport, is_container='container', presence=False, yang_name="map-fport", rest_name="fport", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'alt-name': u'fport'}}, namespace='urn:brocade.com:mgmt:brocade-ag', defining_module='brocade-ag', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """map_fport must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=map_fport.map_fport, is_container='container', presence=False, yang_name="map-fport", rest_name="fport", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'alt-name': u'fport'}}, namespace='urn:brocade.com:mgmt:brocade-ag', defining_module='brocade-ag', yang_type='container', is_config=True)""", }) self.__map_fport = t if hasattr(self, '_set'): self._set()
java
public void deleteMergeRequestDiscussionNote(Object projectIdOrPath, Integer mergeRequestIid, Integer discussionId, Integer noteId) throws GitLabApiException { delete(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "discussions", noteId); }
java
public Iterable<Page> getPagesContainingTemplateNames(List<String> templateNames) throws WikiApiException{ return getFilteredPages(templateNames, true); }
python
def datetime_format(desired_format, datetime_instance=None, *args, **kwargs): """ Replaces format style phrases (listed in the dt_exps dictionary) with this datetime instance's information. .. code :: python reusables.datetime_format("Hey, it's {month-full} already!") "Hey, it's March already!" :param desired_format: string to add datetime details too :param datetime_instance: datetime.datetime instance, defaults to 'now' :param args: additional args to pass to str.format :param kwargs: additional kwargs to pass to str format :return: formatted string """ for strf, exp in datetime_regex.datetime.format.items(): desired_format = exp.sub(strf, desired_format) if not datetime_instance: datetime_instance = now() return datetime_instance.strftime(desired_format.format(*args, **kwargs))
python
def ensure_path(path, mode=0o777): """Ensure that path exists in a multiprocessing safe way. If the path does not exist, recursively create it and its parent directories using the provided mode. If the path already exists, do nothing. The umask is cleared to enable the mode to be set, and then reset to the original value after the mode is set. Parameters ---------- path : str file system path to a non-existent directory that should be created. mode : int octal representation of the mode to use when creating the directory. Raises ------ OSError If os.makedirs raises an OSError for any reason other than if the directory already exists. """ if path: try: umask = os.umask(000) os.makedirs(path, mode) os.umask(umask) except OSError as e: if e.errno != errno.EEXIST: raise
python
def _link_for_value(self, value): '''Returns the linked key if `value` is a link, or None.''' try: key = Key(value) if key.name == self.sentinel: return key.parent except: pass return None
java
public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: java twitter4j.examples.geo.GetGeoDetails [place id]"); System.exit(-1); } try { Twitter twitter = new TwitterFactory().getInstance(); Place place = twitter.getGeoDetails(args[0]); System.out.println("name: " + place.getName()); System.out.println("country: " + place.getCountry()); System.out.println("country code: " + place.getCountryCode()); System.out.println("full name: " + place.getFullName()); System.out.println("id: " + place.getId()); System.out.println("place type: " + place.getPlaceType()); System.out.println("street address: " + place.getStreetAddress()); Place[] containedWithinArray = place.getContainedWithIn(); if (containedWithinArray != null && containedWithinArray.length != 0) { System.out.println(" contained within:"); for (Place containedWithinPlace : containedWithinArray) { System.out.println(" id: " + containedWithinPlace.getId() + " name: " + containedWithinPlace.getFullName()); } } System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to retrieve geo details: " + te.getMessage()); System.exit(-1); } }
python
def _get_fashion_mnist(directory): """Download all FashionMNIST files to directory unless they are there.""" # Fashion mnist files have the same names as MNIST. # We must choose a separate name (by adding 'fashion-' prefix) in the tmp_dir. for filename in [ _MNIST_TRAIN_DATA_FILENAME, _MNIST_TRAIN_LABELS_FILENAME, _MNIST_TEST_DATA_FILENAME, _MNIST_TEST_LABELS_FILENAME ]: generator_utils.maybe_download(directory, _FASHION_MNIST_LOCAL_FILE_PREFIX + filename, _FASHION_MNIST_URL + filename)
java
protected boolean fail(Throwable e) { if (done.compareAndSet(false, true)) { onErrorCore(e); return true; } return false; }
python
def do_startInstance(self,args): """Start specified instance""" parser = CommandArgumentParser("startInstance") parser.add_argument(dest='instance',help='instance index or name'); args = vars(parser.parse_args(args)) instanceId = args['instance'] force = args['force'] try: index = int(instanceId) instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances'] instanceId = instances[index] except ValueError: pass client = AwsConnectionFactory.getEc2Client() client.start_instances(InstanceIds=[instanceId['InstanceId']])
python
def help_center_article_show(self, locale, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/articles#show-article" api_path = "/api/v2/help_center/{locale}/articles/{id}.json" api_path = api_path.format(locale=locale, id=id) return self.call(api_path, **kwargs)
java
@Override public synchronized DatabaseEngine duplicate(Properties mergeProperties, final boolean copyEntities) throws DuplicateEngineException { if (mergeProperties == null) { mergeProperties = new Properties(); } final PdbProperties niwProps = properties.clone(); niwProps.merge(mergeProperties); if (!(niwProps.isSchemaPolicyNone() || niwProps.isSchemaPolicyCreate())) { throw new DuplicateEngineException("Duplicate can only be called if pdb.policy is set to 'create' or 'none'"); } try { DatabaseEngine niw = DatabaseFactory.getConnection(niwProps); if (copyEntities) { for (MappedEntity entity : entities.values()) { niw.addEntity(entity.getEntity()); } } return niw; } catch (final Exception e) { throw new DuplicateEngineException("Could not duplicate connection", e); } }
python
def toggle_lock(self, value): """Lock/Unlock dockwidgets and toolbars""" self.interface_locked = value CONF.set('main', 'panes_locked', value) # Apply lock to panes for plugin in (self.widgetlist + self.thirdparty_plugins): if self.interface_locked: if plugin.dockwidget.isFloating(): plugin.dockwidget.setFloating(False) plugin.dockwidget.setTitleBarWidget(QWidget()) else: plugin.dockwidget.set_title_bar() # Apply lock to toolbars for toolbar in self.toolbarslist: if self.interface_locked: toolbar.setMovable(False) else: toolbar.setMovable(True)
java
public void changeSelected(String selectNode, ServletRequest request) { _selectedNode = TreeHelpers.changeSelected(this, _selectedNode, selectNode, request); }
python
def validate(ctx, schema, all_schemata): """Validates all objects or all objects of a given schema.""" database = ctx.obj['db'] if schema is None: if all_schemata is False: log('No schema given. Read the help', lvl=warn) return else: schemata = database.objectmodels.keys() else: schemata = [schema] for schema in schemata: try: things = database.objectmodels[schema] with click.progressbar(things.find(), length=things.count(), label='Validating %15s' % schema) as object_bar: for obj in object_bar: obj.validate() except Exception as e: log('Exception while validating:', schema, e, type(e), '\n\nFix this object and rerun validation!', emitter='MANAGE', lvl=error) log('Done')
python
def unreserve_resources(role): """ Unreserves all the resources for all the slaves for the role. """ state = dcos_agents_state() if not state or 'slaves' not in state.keys(): return False all_success = True for agent in state['slaves']: if not unreserve_resource(agent, role): all_success = False return all_success
java
private static Geometry splitPolygonWithLine(Polygon polygon, LineString lineString) throws SQLException { Collection<Polygon> pols = polygonWithLineSplitter(polygon, lineString); if (pols != null) { return FACTORY.buildGeometry(polygonWithLineSplitter(polygon, lineString)); } return null; }
python
def tmpl_if(condition, trueval, falseval=u''): """If ``condition`` is nonempty and nonzero, emit ``trueval``; otherwise, emit ``falseval`` (if provided). * synopsis: ``%if{condition,truetext}`` or \ ``%if{condition,truetext,falsetext}`` * description: If condition is nonempty (or nonzero, if it’s a \ number), then returns the second argument. Otherwise, returns the \ third argument if specified (or nothing if falsetext is left off). """ try: int_condition = _int_arg(condition) except ValueError: if condition.lower() == "false": return falseval else: condition = int_condition if condition: return trueval else: return falseval
java
public ConfigBase fromXml(final InputStream is, final Class cl) throws ConfigException { try { return fromXml(parseXml(is), cl); } catch (final ConfigException ce) { throw ce; } catch (final Throwable t) { throw new ConfigException(t); } }
java
protected List<ManagedModule> createAndStartModules() { final List<ManagedModule> managedModuleInstances = new ArrayList<>(); // create and start each managed module for(final Class<? extends ManagedModule> module:managedModules) { final ManagedModule mm = injector.getInstance(module); managedModuleInstances.add(mm); mm.start(); } return managedModuleInstances; }
java
private boolean isSpecTopicMetaData(final String key, final String value) { if (ContentSpecUtilities.isSpecTopicMetaData(key)) { // Abstracts can be plain text so check an opening bracket exists if (key.equalsIgnoreCase(CommonConstants.CS_ABSTRACT_TITLE) || key.equalsIgnoreCase( CommonConstants.CS_ABSTRACT_ALTERNATE_TITLE)) { final String fixedValue = value.trim().replaceAll("(?i)^" + key + "\\s*", ""); return fixedValue.trim().startsWith("["); } else { return true; } } else { return false; } }
java
public static CPDefinitionLink findByUUID_G(String uuid, long groupId) throws com.liferay.commerce.product.exception.NoSuchCPDefinitionLinkException { return getPersistence().findByUUID_G(uuid, groupId); }
java
public boolean isLocalCache(String cacheContainerName, String localCacheName) throws Exception { if (!isCacheContainer(cacheContainerName)) { return false; } Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_INFINISPAN, CACHE_CONTAINER, cacheContainerName); String haystack = LOCAL_CACHE; return null != findNodeInList(addr, haystack, localCacheName); }
java
public com.google.api.ads.admanager.axis.v201805.Date getEndDate() { return endDate; }
python
def set_metadata(self, container, metadata, clear=False, prefix=None): """ Accepts a dictionary of metadata key/value pairs and updates the specified container metadata with them. If 'clear' is True, any existing metadata is deleted and only the passed metadata is retained. Otherwise, the values passed here update the container's metadata. By default, the standard container metadata prefix ('X-Container-Meta-') is prepended to the header name if it isn't present. For non-standard headers, you must include a non-None prefix, such as an empty string. """ # Add the metadata prefix, if needed. if prefix is None: prefix = CONTAINER_META_PREFIX massaged = _massage_metakeys(metadata, prefix) new_meta = {} if clear: curr_meta = self.api.get_container_metadata(container, prefix=prefix) for ckey in curr_meta: new_meta[ckey] = "" utils.case_insensitive_update(new_meta, massaged) name = utils.get_name(container) uri = "/%s" % name resp, resp_body = self.api.method_post(uri, headers=new_meta) return 200 <= resp.status_code <= 299
python
def Set(self, value, context=None): """Receives a value for the object and some context on its source.""" if self.has_error: return if self.value is None: self.value = value self._context["old_value"] = value self._context.update({"old_" + k: v for k, v in context.items()}) elif self.value != value: self.has_error = True self._context["new_value"] = value self._context.update({"new_" + k: v for k, v in context.items()})
python
def _generate_struct_cstor_default(self, struct): """Emits struct convenience constructor. Default arguments are omitted.""" if not self._struct_has_defaults(struct): return fields_no_default = [ f for f in struct.all_fields if not f.has_default and not is_nullable_type(f.data_type) ] with self.block_func( func=self._cstor_name_from_fields(fields_no_default), args=fmt_func_args_from_fields(fields_no_default), return_type='instancetype'): args = ([(fmt_var(f.name), fmt_var(f.name) if not f.has_default and not is_nullable_type(f.data_type) else 'nil') for f in struct.all_fields]) cstor_args = fmt_func_args(args) self.emit('return [self {}:{}];'.format( self._cstor_name_from_fields(struct.all_fields), cstor_args)) self.emit()
java
CacheResourceCore createCore(String path, String name, int type) throws IOException { CacheResourceCore value = new CacheResourceCore(type, path, name); getCache().put(toKey(path, name), value, null, null); return value; }
java
protected final long getClassLastModified() throws IOException, SQLException { String dir=getServletContext().getRealPath("/WEB-INF/classes"); if(dir!=null && dir.length()>0) { // Try to get from the class file long lastMod=new File(dir, getClass().getName().replace('.', File.separatorChar) + ".class").lastModified(); if(lastMod!=0 && lastMod!=-1) return lastMod; } return getUptime(); }
python
def insert(self, packet, time=None, **kwargs): ''' Insert a packet into the database Arguments packet The :class:`ait.core.tlm.Packet` instance to insert into the database time Optional parameter specifying the time value to use when inserting the record into the database. Default case does not provide a time value so Influx defaults to the current time when inserting the record. tags Optional kwargs argument for specifying a dictionary of tags to include when adding the values. Defaults to nothing. ''' fields = {} pd = packet._defn for defn in pd.fields: val = getattr(packet.raw, defn.name) if pd.history and defn.name in pd.history: val = getattr(packet.history, defn.name) if val is not None and not (isinstance(val, float) and math.isnan(val)): fields[defn.name] = val if len(fields) == 0: log.error('No fields present to insert into Influx') return tags = kwargs.get('tags', {}) if isinstance(time, dt.datetime): time = time.strftime("%Y-%m-%dT%H:%M:%S") data = { 'measurement': pd.name, 'tags': tags, 'fields': fields } if time: data['time'] = time self._conn.write_points([data])
java
static <S extends ScopeType<S>> boolean isScopeAncestor(ScopeWrapper<S> scope, ScopeWrapper<S> possibleAncestor) { Queue<ScopeWrapper<S>> ancestors = new LinkedList<>(); ancestors.add(scope); while (true) { if (ancestors.isEmpty()) { return false; } if (ancestors.peek().equals(possibleAncestor)) { return true; } ancestors.addAll(ancestors.poll().getParentScopes()); } }
python
def application_id(self, app_id): """Validate request application id matches true application id. Verifying the Application ID matches: https://goo.gl/qAdqe4. Args: app_id: str. Request application_id. Returns: bool: True if valid, False otherwise. """ if self.app_id != app_id: warnings.warn('Application ID is invalid.') return False return True
java
public void cancel() { if (!isCancelled) { isCancelled = true; IntSet segmentsCopy = getUnfinishedSegments(); synchronized (segments) { unfinishedSegments.clear(); } if (trace) { log.tracef("Cancelling inbound state transfer from %s with unfinished segments %s", source, segmentsCopy); } sendCancelCommand(segmentsCopy); notifyCompletion(false); } }
python
def _fake_openassociatorinstancepaths(self, namespace, **params): # pylint: disable=invalid-name """ Implements WBEM server responder for :meth:`~pywbem.WBEMConnection.OpenAssociatorInstancePaths` with data from the instance repository. """ self._validate_namespace(namespace) self._validate_open_params(**params) params['ObjectName'] = params['InstanceName'] del params['InstanceName'] result = self._fake_associatornames(namespace, **params) objects = [] if result is None else [x[2] for x in result[0][2]] return self._open_response(objects, namespace, 'PullInstancePaths', **params)
python
def run(name, chip_bam, input_bam, genome_build, out_dir, method, resources, data): """ Run macs2 for chip and input samples avoiding errors due to samples. """ # output file name need to have the caller name config = dd.get_config(data) out_file = os.path.join(out_dir, name + "_peaks_macs2.xls") macs2_file = os.path.join(out_dir, name + "_peaks.xls") if utils.file_exists(out_file): _compres_bdg_files(out_dir) return _get_output_files(out_dir) macs2 = config_utils.get_program("macs2", config) options = " ".join(resources.get("macs2", {}).get("options", "")) genome_size = bam.fasta.total_sequence_length(dd.get_ref_file(data)) genome_size = "" if options.find("-g") > -1 else "-g %s" % genome_size paired = "-f BAMPE" if bam.is_paired(chip_bam) else "" with utils.chdir(out_dir): cmd = _macs2_cmd(method) try: do.run(cmd.format(**locals()), "macs2 for %s" % name) utils.move_safe(macs2_file, out_file) except subprocess.CalledProcessError: raise RuntimeWarning("macs2 terminated with an error.\n" "Please, check the message and report " "error if it is related to bcbio.\n" "You can add specific options for the sample " "setting resources as explained in docs: " "https://bcbio-nextgen.readthedocs.org/en/latest/contents/configuration.html#sample-specific-resources") _compres_bdg_files(out_dir) return _get_output_files(out_dir)
java
public ServiceFuture<GetPersonalPreferencesResponseInner> getPersonalPreferencesAsync(String userName, PersonalPreferencesOperationsPayload personalPreferencesOperationsPayload, final ServiceCallback<GetPersonalPreferencesResponseInner> serviceCallback) { return ServiceFuture.fromResponse(getPersonalPreferencesWithServiceResponseAsync(userName, personalPreferencesOperationsPayload), serviceCallback); }
python
def p_assignlist(self,t): "assignlist : assignlist ',' assign \n | assign" if len(t)==4: t[0] = t[1] + [t[3]] elif len(t)==2: t[0] = [t[1]] else: raise NotImplementedError('unk_len', len(t)) # pragma: no cover
java
public static void cacheCriteriaByMapping(Class<?> targetClass, Criteria criteria) { Mapping m = GrailsDomainBinder.getMapping(targetClass); if (m != null && m.getCache() != null && m.getCache().getEnabled()) { criteria.setCacheable(true); } }
java
public static boolean isAbsolutePath(String systemId) { if(systemId == null) return false; final File file = new File(systemId); return file.isAbsolute(); }
java
public static int parseIntOrDefault(final String value, final int defaultValue) { if (null == value) { return defaultValue; } return Integer.parseInt(value); }
java
public int filterObject(CaptureSearchResult r) { recordsScanned++; if(recordsScanned > maxRecordsToScan) { LOGGER.warning("Hit max results on " + r.getUrlKey() + " " + r.getCaptureTimestamp()); return FILTER_ABORT; } return FILTER_INCLUDE; }
python
def fetch_datatype(self, bucket, key, r=None, pr=None, basic_quorum=None, notfound_ok=None, timeout=None, include_context=None): """ Fetches a Riak Datatype. """ raise NotImplementedError
java
private static int getMultiplier(final String unit) { int multiplier = 1; if(!StringUtils.isBlank(unit)) { if(UNIT_MILLION.equalsIgnoreCase(unit.trim())) { multiplier = 1000000; } if(UNIT_THOUSAND.equalsIgnoreCase(unit.trim())) { multiplier = 1000; } } return multiplier; }
java
@Override public CommerceDiscount findByLtE_S_First(Date expirationDate, int status, OrderByComparator<CommerceDiscount> orderByComparator) throws NoSuchDiscountException { CommerceDiscount commerceDiscount = fetchByLtE_S_First(expirationDate, status, orderByComparator); if (commerceDiscount != null) { return commerceDiscount; } StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("expirationDate="); msg.append(expirationDate); msg.append(", status="); msg.append(status); msg.append("}"); throw new NoSuchDiscountException(msg.toString()); }
python
def round(self, decimals=0, *args, **kwargs): """ Round each value in Panel to a specified number of decimal places. .. versionadded:: 0.18.0 Parameters ---------- decimals : int Number of decimal places to round to (default: 0). If decimals is negative, it specifies the number of positions to the left of the decimal point. Returns ------- Panel object See Also -------- numpy.around """ nv.validate_round(args, kwargs) if is_integer(decimals): result = np.apply_along_axis(np.round, 0, self.values) return self._wrap_result(result, axis=0) raise TypeError("decimals must be an integer")
java
public String getTrack(int type) { if (allow(type&ID3V1)) { return Integer.toString(id3v1.getTrack()); } if (allow(type&ID3V2)) { return id3v2.getFrameDataString(ID3v2Frames.TRACK_NUMBER); } return null; }
python
def long2ip(l): """Convert a network byte order 32-bit integer to a dotted quad ip address. >>> long2ip(2130706433) '127.0.0.1' >>> long2ip(MIN_IP) '0.0.0.0' >>> long2ip(MAX_IP) '255.255.255.255' >>> long2ip(None) #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TypeError: unsupported operand type(s) for >>: 'NoneType' and 'int' >>> long2ip(-1) #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TypeError: expected int between 0 and 4294967295 inclusive >>> long2ip(374297346592387463875) #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TypeError: expected int between 0 and 4294967295 inclusive >>> long2ip(MAX_IP + 1) #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... TypeError: expected int between 0 and 4294967295 inclusive :param l: Network byte order 32-bit integer. :type l: int :returns: Dotted-quad ip address (eg. '127.0.0.1'). :raises: TypeError """ if MAX_IP < l or l < MIN_IP: raise TypeError( "expected int between %d and %d inclusive" % (MIN_IP, MAX_IP)) return '%d.%d.%d.%d' % ( l >> 24 & 255, l >> 16 & 255, l >> 8 & 255, l & 255)
java
public com.google.api.ads.adwords.axis.v201809.mcm.ManagedCustomerServiceErrorReason getReason() { return reason; }
java
public static <T extends Tree> Matcher<T> isSubtypeOf(Class<?> clazz) { return new IsSubtypeOf<>(typeFromClass(clazz)); }
java
static <T1> Flowable<Notification<CallableResultSet1<T1>>> createWithOneResultSet(Single<Connection> connection, String sql, Flowable<List<Object>> parameterGroups, List<ParameterPlaceholder> parameterPlaceholders, Function<? super ResultSet, ? extends T1> f1, int fetchSize) { return connection.toFlowable().flatMap( con -> createWithOneResultSet(con, sql, parameterGroups, parameterPlaceholders, f1, fetchSize)); }
python
def CopyMicrosecondsToFractionOfSecond(cls, microseconds): """Copies the number of microseconds to a fraction of second value. Args: microseconds (int): number of microseconds. Returns: decimal.Decimal: fraction of second, which must be a value between 0.0 and 1.0. Raises: ValueError: if the number of microseconds is out of bounds. """ if microseconds < 0 or microseconds >= definitions.MICROSECONDS_PER_SECOND: raise ValueError( 'Number of microseconds value: {0:d} out of bounds.'.format( microseconds)) milliseconds, _ = divmod( microseconds, definitions.MICROSECONDS_PER_MILLISECOND) return decimal.Decimal(milliseconds) / definitions.MILLISECONDS_PER_SECOND
java
private String[] extractAndDecodeHeader(String header) throws IOException { byte[] base64Token = header.substring(6).getBytes(CREDENTIALS_CHARSET); byte[] decoded; try { decoded = Base64.decode(base64Token); } catch (IllegalArgumentException e) { throw new BadCredentialsException("Failed to decode basic authentication token"); } String token = new String(decoded, CREDENTIALS_CHARSET); int delim = token.indexOf(":"); if (delim == -1) { throw new BadCredentialsException("Invalid basic authentication token"); } return new String[] {token.substring(0, delim), token.substring(delim + 1)}; }
java
public NYTCorpusDocument parseNYTCorpusDocumentFromFile(File file, boolean validating) { Document document = null; if (validating) { document = loadValidating(file); } else { document = loadNonValidating(file); } return parseNYTCorpusDocumentFromDOMDocument(file, document); }
java
private static AbstractPlanNode injectIndexedJoinWithMaterializedScan( AbstractExpression listElements, IndexScanPlanNode scanNode) { MaterializedScanPlanNode matScan = new MaterializedScanPlanNode(); assert(listElements instanceof VectorValueExpression || listElements instanceof ParameterValueExpression); matScan.setRowData(listElements); matScan.setSortDirection(scanNode.getSortDirection()); NestLoopIndexPlanNode nlijNode = new NestLoopIndexPlanNode(); nlijNode.setJoinType(JoinType.INNER); nlijNode.addInlinePlanNode(scanNode); nlijNode.addAndLinkChild(matScan); // resolve the sort direction nlijNode.resolveSortDirection(); return nlijNode; }
python
def suits_with_dtype(mn, mx, dtype): """ Check whether range of values can be stored into defined data type. :param mn: range minimum :param mx: range maximum :param dtype: :return: """ type_info = np.iinfo(dtype) if mx <= type_info.max and mn >= type_info.min: return True else: return False