language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static LocalCall<String> getUid(String path, boolean followSymlinks) { Map<String, Object> args = new LinkedHashMap<>(); args.put("path", path); args.put("follow_symlinks", followSymlinks); return new LocalCall<>("file.get_uid", Optional.empty(), Optional.of(args), new TypeToken<String>(){}); }
java
public static <T extends ImageGray<T>, D extends ImageGray<D>> InterestPointDetector<T> wrapPoint(GeneralFeatureDetector<T, D> feature, double scale , Class<T> inputType, Class<D> derivType) { ImageGradient<T, D> gradient = null; ImageHessian<D> hessian = null; if (feature.getRequiresGradient() || feature.getRequiresHessian()) gradient = FactoryDerivative.sobel(inputType, derivType); if (feature.getRequiresHessian()) hessian = FactoryDerivative.hessianSobel(derivType); return new GeneralToInterestPoint<>(feature, gradient, hessian, scale, derivType); }
python
def output_summary(self, output_stream=sys.stdout): """outputs a usage tip and the list of acceptable commands. This is useful as the output of the 'help' option. parameters: output_stream - an open file-like object suitable for use as the target of a print function """ if self.app_name or self.app_description: print('Application: ', end='', file=output_stream) if self.app_name: print(self.app_name, self.app_version, file=output_stream) if self.app_description: print(self.app_description, file=output_stream) if self.app_name or self.app_description: print('', file=output_stream) names_list = self.get_option_names() print( "usage:\n%s [OPTIONS]... " % self.app_invocation_name, end='', file=output_stream ) bracket_count = 0 # this section prints the non-switch command line arguments for key in names_list: an_option = self.option_definitions[key] if an_option.is_argument: if an_option.default is None: # there's no option, assume the user must set this print(an_option.name, end='', file=output_stream) elif ( inspect.isclass(an_option.value) or inspect.ismodule(an_option.value) ): # this is already set and it could have expanded, most # likely this is a case where a sub-command has been # loaded and we're looking to show the help for it. # display show it as a constant already provided rather # than as an option the user must provide print(an_option.default, end='', file=output_stream) else: # this is an argument that the user may alternatively # provide print("[ %s" % an_option.name, end='', file=output_stream) bracket_count += 1 print(']' * bracket_count, '\n', file=output_stream) names_list.sort() if names_list: print('OPTIONS:', file=output_stream) pad = ' ' * 4 for name in names_list: if name in self.options_banned_from_help: continue option = self._get_option(name) line = ' ' * 2 # always start with 2 spaces if option.short_form: line += '-%s, ' % option.short_form line += '--%s' % name line += '\n' doc = option.doc if option.doc is not None else '' if doc: line += '%s%s\n' % (pad, doc) try: value = option.value type_of_value = type(value) converter_function = to_string_converters[type_of_value] default = converter_function(value) except KeyError: default = option.value if default is not None: if ( (option.secret or 'password' in name.lower()) and not self.option_definitions.admin.expose_secrets.default ): default = '*********' if name not in ('help',): # don't bother with certain dead obvious ones line += '%s(default: %s)\n' % (pad, default) print(line, file=output_stream)
python
def get_devices(self, refresh=False, generic_type=None): """Get all devices from Abode.""" if refresh or self._devices is None: if self._devices is None: self._devices = {} _LOGGER.info("Updating all devices...") response = self.send_request("get", CONST.DEVICES_URL) response_object = json.loads(response.text) if (response_object and not isinstance(response_object, (tuple, list))): response_object = [response_object] _LOGGER.debug("Get Devices Response: %s", response.text) for device_json in response_object: # Attempt to reuse an existing device device = self._devices.get(device_json['id']) # No existing device, create a new one if device: device.update(device_json) else: device = new_device(device_json, self) if not device: _LOGGER.debug( "Skipping unknown device: %s", device_json) continue self._devices[device.device_id] = device # We will be treating the Abode panel itself as an armable device. panel_response = self.send_request("get", CONST.PANEL_URL) panel_json = json.loads(panel_response.text) self._panel.update(panel_json) _LOGGER.debug("Get Mode Panel Response: %s", response.text) alarm_device = self._devices.get(CONST.ALARM_DEVICE_ID + '1') if alarm_device: alarm_device.update(panel_json) else: alarm_device = ALARM.create_alarm(panel_json, self) self._devices[alarm_device.device_id] = alarm_device if generic_type: devices = [] for device in self._devices.values(): if (device.generic_type is not None and device.generic_type in generic_type): devices.append(device) return devices return list(self._devices.values())
python
def handle(self): """ Executes the command. """ if not self.confirm_to_proceed( "<question>Are you sure you want to refresh the database?:</question> " ): return database = self.option("database") options = [("--force", True)] if self.option("path"): options.append(("--path", self.option("path"))) if database: options.append(("--database", database)) if self.get_definition().has_option("config"): options.append(("--config", self.option("config"))) self.call("migrate:reset", options) self.call("migrate", options) if self._needs_seeding(): self._run_seeder(database)
python
def _get_next_occurrence(haystack, offset, needles): """ Find next occurence of one of the needles in the haystack :return: tuple of (index, needle found) or: None if no needle was found""" # make map of first char to full needle (only works if all needles # have different first characters) firstcharmap = dict([(n[0], n) for n in needles]) firstchars = firstcharmap.keys() while offset < len(haystack): if haystack[offset] in firstchars: possible_needle = firstcharmap[haystack[offset]] if haystack[offset:offset + len(possible_needle)] == possible_needle: return offset, possible_needle offset += 1 return None
python
def makeblastdb(self, fastapath): """ Makes blast database files from targets as necessary """ # remove the path and the file extension for easier future globbing db = fastapath.split('.')[0] nhr = '{}.nhr'.format(db) # add nhr for searching if not os.path.isfile(str(nhr)): # if check for already existing dbs # Create the databases threadlock = threading.Lock() command = 'makeblastdb -in {} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {}'.format(fastapath, db) out, err = run_subprocess(command) threadlock.acquire() write_to_logfile(out, err, self.logfile) threadlock.release() dotter()
python
def json_to_string(self, source): """ Serialize JSON structure into string. *Args:*\n _source_ - JSON structure *Returns:*\n JSON string *Raises:*\n JsonValidatorError *Example:*\n | *Settings* | *Value* | | Library | JsonValidator | | Library | OperatingSystem | | *Test Cases* | *Action* | *Argument* | *Argument* | | Json to string | ${json_string}= | OperatingSystem.Get File | ${CURDIR}${/}json_example.json | | | ${json}= | String to json | ${json_string} | | | ${string}= | Json to string | ${json} | | | ${pretty_string}= | Pretty print json | ${string} | | | Log to console | ${pretty_string} | """ try: load_input_json = json.dumps(source) except ValueError as e: raise JsonValidatorError("Could serialize '%s' to JSON: %s" % (source, e)) return load_input_json
java
public static <T, F> FieldAugment<T, F> augment(Class<T> type, Class<? super F> fieldType, String name) { checkNotNull(type, "type"); checkNotNull(fieldType, "fieldType"); checkNotNull(name, "name"); @SuppressWarnings("unchecked") F defaultValue = (F) getDefaultValue(fieldType); FieldAugment<T, F> ret = tryCreateReflectionAugment(type, fieldType, name, defaultValue); return ret != null ? ret : new MapFieldAugment<T, F>(defaultValue); }
java
public static Config getConfig(@Nonnull final URI configLocation, @Nullable final String configName) { final ConfigFactory configFactory = new ConfigFactory(configLocation, configName); return new Config(configFactory.load()); }
python
def crc_ihex(hexstr): """Calculate the CRC for given Intel HEX hexstring. """ crc = sum(bytearray(binascii.unhexlify(hexstr))) crc &= 0xff crc = ((~crc + 1) & 0xff) return crc
python
def draw(self, filename, color=True): ''' Render a plot of the graph via pygraphviz. Args: filename (str): Path to save the generated image to. color (bool): If True, will color graph nodes based on their type, otherwise will draw a black-and-white graph. ''' verify_dependencies(['pgv']) if not hasattr(self, '_results'): raise RuntimeError("Graph cannot be drawn before it is executed. " "Try calling run() first.") g = pgv.AGraph(directed=True) g.node_attr['colorscheme'] = 'set312' for elem in self._results: if not hasattr(elem, 'history'): continue log = elem.history while log: # Configure nodes source_from = log.parent[6] if log.parent else '' s_node = hash((source_from, log[2])) s_color = stim_list.index(log[2]) s_color = s_color % 12 + 1 t_node = hash((log[6], log[7])) t_style = 'filled,' if color else '' t_style += 'dotted' if log.implicit else '' if log[6].endswith('Extractor'): t_color = '#0082c8' elif log[6].endswith('Filter'): t_color = '#e6194b' else: t_color = '#3cb44b' r_node = hash((log[6], log[5])) r_color = stim_list.index(log[5]) r_color = r_color % 12 + 1 # Add nodes if color: g.add_node(s_node, label=log[2], shape='ellipse', style='filled', fillcolor=s_color) g.add_node(t_node, label=log[6], shape='box', style=t_style, fillcolor=t_color) g.add_node(r_node, label=log[5], shape='ellipse', style='filled', fillcolor=r_color) else: g.add_node(s_node, label=log[2], shape='ellipse') g.add_node(t_node, label=log[6], shape='box', style=t_style) g.add_node(r_node, label=log[5], shape='ellipse') # Add edges g.add_edge(s_node, t_node, style=t_style) g.add_edge(t_node, r_node, style=t_style) log = log.parent g.draw(filename, prog='dot')
python
def create(self, image, command=None, **kwargs): """ Create a container without starting it. Similar to ``docker create``. Takes the same arguments as :py:meth:`run`, except for ``stdout``, ``stderr``, and ``remove``. Returns: A :py:class:`Container` object. Raises: :py:class:`docker.errors.ImageNotFound` If the specified image does not exist. :py:class:`docker.errors.APIError` If the server returns an error. """ if isinstance(image, Image): image = image.id kwargs['image'] = image kwargs['command'] = command kwargs['version'] = self.client.api._version create_kwargs = _create_container_args(kwargs) resp = self.client.api.create_container(**create_kwargs) return self.get(resp['Id'])
python
def section(self, section_title): ''' Get the plain text content of a section from `self.sections`. Returns None if `section_title` isn't found, otherwise returns a whitespace stripped string. This is a convenience method that wraps self.content. .. warning:: Calling `section` on a section that has subheadings will NOT return the full text of all of the subsections. It only gets the text between `section_title` and the next subheading, which is often empty. ''' section = u"== {} ==".format(section_title) try: index = self.content.index(section) + len(section) except ValueError: return None try: next_index = self.content.index("==", index) except ValueError: next_index = len(self.content) return self.content[index:next_index].lstrip("=").strip()
java
@Override public Request<DeleteVpnConnectionRequest> getDryRunRequest() { Request<DeleteVpnConnectionRequest> request = new DeleteVpnConnectionRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
python
def _validate_input_data(self, data, request): """ Validate input data. :param request: the HTTP request :param data: the parsed data :return: if validation is performed and succeeds the data is converted into whatever format the validation uses (by default Django's Forms) If not, the data is returned unchanged. :raises: HttpStatusCodeError if data is not valid """ validator = self._get_input_validator(request) if isinstance(data, (list, tuple)): return map(validator.validate, data) else: return validator.validate(data)
java
static void setHost(String scheme, String host, int port) { BASE_URL = scheme + "://" + host + ":" + port + "/" + VERSION + "/"; }
java
@Deprecated // to force even if someone wants to remove the one from the class @Restricted(NoExternalUse.class) public static @Nonnull ApiTokenStats load(@CheckForNull File parent) { // even if we are not using statistics, we load the existing one in case the configuration // is enabled afterwards to avoid erasing data if (parent == null) { return new ApiTokenStats(); } ApiTokenStats apiTokenStats = internalLoad(parent); if (apiTokenStats == null) { apiTokenStats = new ApiTokenStats(); } apiTokenStats.setParent(parent); return apiTokenStats; }
java
public static int writeInt(ArrayView target, int offset, int value) { return writeInt(target.array(), target.arrayOffset() + offset, value); }
java
public void marshall(ListTriggersRequest listTriggersRequest, ProtocolMarshaller protocolMarshaller) { if (listTriggersRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listTriggersRequest.getNextToken(), NEXTTOKEN_BINDING); protocolMarshaller.marshall(listTriggersRequest.getDependentJobName(), DEPENDENTJOBNAME_BINDING); protocolMarshaller.marshall(listTriggersRequest.getMaxResults(), MAXRESULTS_BINDING); protocolMarshaller.marshall(listTriggersRequest.getTags(), TAGS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
public java.util.List<AccountWithRestoreAccess> getAccountsWithRestoreAccess() { if (accountsWithRestoreAccess == null) { accountsWithRestoreAccess = new com.amazonaws.internal.SdkInternalList<AccountWithRestoreAccess>(); } return accountsWithRestoreAccess; }
java
public static MessageHandler signallingMessageHandler(final ProcessEngine processEngine) { return new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { String executionId = message.getHeaders().containsKey("executionId") ? (String) message.getHeaders().get("executionId") : (String) null; if (null != executionId) processEngine.getRuntimeService().trigger(executionId); } }; }
python
def add_widget(self, widget=None, row=None, col=None, row_span=1, col_span=1, **kwargs): """ Add a new widget to this grid. This will cause other widgets in the grid to be resized to make room for the new widget. Can be used to replace a widget as well Parameters ---------- widget : Widget | None The Widget to add. New widget is constructed if widget is None. row : int The row in which to add the widget (0 is the topmost row) col : int The column in which to add the widget (0 is the leftmost column) row_span : int The number of rows to be occupied by this widget. Default is 1. col_span : int The number of columns to be occupied by this widget. Default is 1. **kwargs : dict parameters sent to the new Widget that is constructed if widget is None Notes ----- The widget's parent is automatically set to this grid, and all other parent(s) are removed. """ if row is None: row = self._next_cell[0] if col is None: col = self._next_cell[1] if widget is None: widget = Widget(**kwargs) else: if kwargs: raise ValueError("cannot send kwargs if widget is given") _row = self._cells.setdefault(row, {}) _row[col] = widget self._grid_widgets[self._n_added] = (row, col, row_span, col_span, widget) self._n_added += 1 widget.parent = self self._next_cell = [row, col+col_span] widget._var_w = Variable("w-(row: %s | col: %s)" % (row, col)) widget._var_h = Variable("h-(row: %s | col: %s)" % (row, col)) # update stretch based on colspan/rowspan # usually, if you make something consume more grids or columns, # you also want it to actually *take it up*, ratio wise. # otherwise, it will never *use* the extra rows and columns, # thereby collapsing the extras to 0. stretch = list(widget.stretch) stretch[0] = col_span if stretch[0] is None else stretch[0] stretch[1] = row_span if stretch[1] is None else stretch[1] widget.stretch = stretch self._need_solver_recreate = True return widget
java
private void flushEventBuffer() { Holder<T> holder = buffer.get(); logger.accept(holder.getBuffer().get()); holder.clear(); }
java
public ConstructorDoc[] constructors(boolean filter) { Names names = tsym.name.table.names; List<ConstructorDocImpl> constructors = List.nil(); for (Symbol sym : tsym.members().getSymbols(NON_RECURSIVE)) { if (sym != null && sym.kind == MTH && sym.name == names.init) { MethodSymbol s = (MethodSymbol)sym; if (!filter || env.shouldDocument(s)) { constructors = constructors.prepend(env.getConstructorDoc(s)); } } } //### Cache constructors here? return constructors.toArray(new ConstructorDocImpl[constructors.length()]); }
python
def cast_values_csvs(d, idx, x): """ Attempt to cast string to float. If error, keep as a string. :param dict d: Data :param int idx: Index number :param str x: Data :return any: """ try: d[idx].append(float(x)) except ValueError: d[idx].append(x) # logger_misc.warn("cast_values_csv: ValueError") # logger_misc.warn("ValueError: col: {}, {}".format(x, e)) except KeyError as e: logger_misc.warn("cast_values_csv: KeyError: col: {}, {}".format(x, e)) return d
python
def file_handle(fnh, mode="rU"): """ Takes either a file path or an open file handle, checks validity and returns an open file handle or raises an appropriate Exception. :type fnh: str :param fnh: It is the full path to a file, or open file handle :type mode: str :param mode: The way in which this file will be used, for example to read or write or both. By default, file will be opened in rU mode. :return: Returns an opened file for appropriate usage. """ handle = None if isinstance(fnh, file): if fnh.closed: raise ValueError("Input file is closed.") handle = fnh elif isinstance(fnh, str): handle = open(fnh, mode) return handle
java
public static void insertEditEmpty( PageContext context, I_CmsXmlContentContainer container, CmsDirectEditMode mode, String id) throws CmsException, JspException { ServletRequest req = context.getRequest(); if (isEditableRequest(req) && (container.getCollectorResult() != null) && (container.getCollectorResult().size() == 0)) { CmsFlexController controller = CmsFlexController.getController(req); CmsObject cms = controller.getCmsObject(); // now collect the resources I_CmsResourceCollector collector = OpenCms.getResourceManager().getContentCollector( container.getCollectorName()); if (collector == null) { throw new CmsException( Messages.get().container(Messages.ERR_COLLECTOR_NOT_FOUND_1, container.getCollectorName())); } String createParam = collector.getCreateParam( cms, container.getCollectorName(), container.getCollectorParam()); String createLink = collector.getCreateLink( cms, container.getCollectorName(), container.getCollectorParam()); if ((createParam != null) && (collector.getCreateTypeId( cms, container.getCollectorName(), container.getCollectorParam()) != -1)) { String createFolderName = CmsResource.getFolderPath(createLink); createParam = CmsEncoder.encode(container.getCollectorName() + "|" + createParam); CmsDirectEditParams params = new CmsDirectEditParams( createFolderName, CmsDirectEditButtonSelection.NEW, mode, createParam); params.setId(id); params.setCollectorName(container.getCollectorName()); params.setCollectorParams(container.getCollectorParam()); getDirectEditProvider(context).insertDirectEditEmptyList(context, params); } } }
java
public static BaseException translateException(Exception exception) { if (exception instanceof BaseException) { return (BaseException) exception; } else { for (SeedExceptionTranslator exceptionTranslator : exceptionTranslators) { if (exceptionTranslator.canTranslate(exception)) { return exceptionTranslator.translate(exception); } } return SeedException.wrap(exception, CoreErrorCode.UNEXPECTED_EXCEPTION); } }
python
def gene_id_check(genes, errors, columns, row_number): """ Validate gene identifiers against a known set. Parameters ---------- genes : set The known set of gene identifiers. errors : Passed by goodtables. columns : Passed by goodtables. row_number : Passed by goodtables. """ message = ("Gene '{value}' in column {col} and row {row} does not " "appear in the metabolic model.") for column in columns: if "gene" in column['header'] and column['value'] not in genes: message = message.format( value=column['value'], row=row_number, col=column['number']) errors.append({ 'code': 'bad-value', 'message': message, 'row-number': row_number, 'column-number': column['number'], })
java
public void downloadRange(OutputStream output, long rangeStart, long rangeEnd) { this.downloadRange(output, rangeStart, rangeEnd, null); }
python
def decode_full_layer_uri(full_layer_uri_string): """Decode the full layer URI. :param full_layer_uri_string: The full URI provided by our helper. :type full_layer_uri_string: basestring :return: A tuple with the QGIS URI and the provider key. :rtype: tuple """ if not full_layer_uri_string: return None, None split = full_layer_uri_string.split('|qgis_provider=') if len(split) == 1: return split[0], None else: return split
python
def SMGetJobDictionaries(self, domain='kSMDomainSystemLaunchd'): """Copy all Job Dictionaries from the ServiceManagement. Args: domain: The name of a constant in Foundation referencing the domain. Will copy all launchd services by default. Returns: A marshalled python list of dicts containing the job dictionaries. """ cfstring_launchd = ctypes.c_void_p.in_dll(self.dll, domain) return CFArray(self.dll.SMCopyAllJobDictionaries(cfstring_launchd))
java
public ManagedDatabaseInner beginUpdate(String resourceGroupName, String managedInstanceName, String databaseName, ManagedDatabaseUpdate parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, parameters).toBlocking().single().body(); }
python
def _access_through_series(values, name): """Coerce an array of datetime-like values to a pandas Series and access requested datetime component """ values_as_series = pd.Series(values.ravel()) if name == "season": months = values_as_series.dt.month.values field_values = _season_from_months(months) else: field_values = getattr(values_as_series.dt, name).values return field_values.reshape(values.shape)
java
@Override public CommerceWishList[] findByUserId_PrevAndNext( long commerceWishListId, long userId, OrderByComparator<CommerceWishList> orderByComparator) throws NoSuchWishListException { CommerceWishList commerceWishList = findByPrimaryKey(commerceWishListId); Session session = null; try { session = openSession(); CommerceWishList[] array = new CommerceWishListImpl[3]; array[0] = getByUserId_PrevAndNext(session, commerceWishList, userId, orderByComparator, true); array[1] = commerceWishList; array[2] = getByUserId_PrevAndNext(session, commerceWishList, userId, orderByComparator, false); return array; } catch (Exception e) { throw processException(e); } finally { closeSession(session); } }
java
@Override public void endElement(CMLStack xpath, String uri, String name, String raw) { if (name.equals("molecule")) { // System.out.println("Ending element mdmolecule"); // add chargeGroup, and then delete them if (currentChargeGroup != null) { if (currentMolecule instanceof MDMolecule) { ((MDMolecule) currentMolecule).addChargeGroup(currentChargeGroup); } else { logger.error("Need to store a charge group, but the current molecule is not a MDMolecule!"); } currentChargeGroup = null; } else // add chargeGroup, and then delete them if (currentResidue != null) { if (currentMolecule instanceof MDMolecule) { ((MDMolecule) currentMolecule).addResidue(currentResidue); } else { logger.error("Need to store a residue group, but the current molecule is not a MDMolecule!"); } currentResidue = null; } else { // System.out.println("OK, that was the last end mdmolecule"); super.endElement(xpath, uri, name, raw); } } else if ("atomArray".equals(name)) { if (xpath.length() == 2 && xpath.endsWith("molecule", "atomArray")) { storeAtomData(); newAtomData(); } else if (xpath.length() > 2 && xpath.endsWith("cml", "molecule", "atomArray")) { storeAtomData(); newAtomData(); } } else if ("bondArray".equals(name)) { if (xpath.length() == 2 && xpath.endsWith("molecule", "bondArray")) { storeBondData(); newBondData(); } else if (xpath.length() > 2 && xpath.endsWith("cml", "molecule", "bondArray")) { storeBondData(); newBondData(); } } else if ("scalar".equals(name)) { //Residue number if ("md:resNumber".equals(DICTREF)) { int myInt = Integer.parseInt(currentChars); currentResidue.setNumber(myInt); } //ChargeGroup number else if ("md:cgNumber".equals(DICTREF)) { int myInt = Integer.parseInt(currentChars); currentChargeGroup.setNumber(myInt); } } else { super.endElement(xpath, uri, name, raw); } }
python
def fixture_to_tables(fixture): """ convert fixture into *behave* examples :param fixture: a dictionary in the following form:: { "test1name": { "test1property1": ..., "test1property2": ..., ... }, "test2name": { "test2property1": ..., "test2property2": ..., ... } } :return: a list, with each item represent a table: `(caption, rows)`, each item in `rows` is `(col1, col2,...)` """ tables = [] for (title, content) in fixture.iteritems(): rows = [] # header(keyword) row keys = sorted(content.keys()) rows.append(tuple(keys)) # item(value) row row1 = [] for col in rows[0]: row1.append(content[col]) rows.append(tuple(row1)) tables.append((title, tuple(rows))) return tables
python
def optional(p, default_value=None): '''`Make a parser as optional. If success, return the result, otherwise return default_value silently, without raising any exception. If default_value is not provided None is returned instead. ''' @Parser def optional_parser(text, index): res = p(text, index) if res.status: return Value.success(res.index, res.value) else: # Return the maybe existing default value without doing anything. return Value.success(res.index, default_value) return optional_parser
java
@Override public double distance(NumberVector v1, NumberVector v2) { return 1 - PearsonCorrelation.coefficient(v1, v2); }
python
def change_setting(self, instance_name, key, raw_value): """ Change the settings <key> to <raw_value> of an instance named <instance_name>. <raw_value> should be a string and is properly converted. """ ii = self.insts[instance_name] mo = self.modules[ii.module] if key in mo.deps: if raw_value not in self.insts: raise ValueError("No such instance %s" % raw_value) vii = self.insts[raw_value] vmo = self.modules[vii.module] if not (mo.deps[key].type in vmo.inherits or mo.deps[key].type == vii.module): raise ValueError("%s isn't a %s" % ( raw_value, mo.deps[key].type)) value = vii.object elif key in mo.vsettings: value = self.valueTypes[mo.vsettings[key].type]( raw_value) else: raise ValueError("No such settings %s" % key) self.l.info("Changing %s.%s to %s" % (instance_name, key, raw_value)) ii.settings[key] = value ii.object.change_setting(key, value)
java
public <T> T parse(Reader in, JsonReaderI<T> mapper) throws ParseException { this.base = mapper.base; // this.in = in; return super.parse(mapper); }
python
def _strip_stray_atoms(self): """Remove stray atoms and surface pieces. """ components = self.bond_graph.connected_components() major_component = max(components, key=len) for atom in list(self.particles()): if atom not in major_component: self.remove(atom)
java
public MAP outboundMap(Map<String, Object> ctx) { AddressingProperties implementation = (AddressingProperties)ctx.get(CXFMAPConstants.CLIENT_ADDRESSING_PROPERTIES_OUTBOUND); if (implementation == null) { implementation = new AddressingProperties(); ctx.put(CXFMAPConstants.CLIENT_ADDRESSING_PROPERTIES, implementation); ctx.put(CXFMAPConstants.CLIENT_ADDRESSING_PROPERTIES_OUTBOUND, implementation); } return newMap(implementation); }
python
def _GetNameFromProduct(self): """Determines the predefined operating system name from the product. Returns: str: operating system name, such as "macOS Mojave" or "Windows XP" or None if the name cannot be determined. This value is used to programmatically link a parser preset to an operating system and therefore must be one of predefined values. """ product = self.product or '' product = product.split(' ') product_lower_case = [segment.lower() for segment in product] number_of_segments = len(product) if 'windows' in product_lower_case: segment_index = product_lower_case.index('windows') + 1 if product_lower_case[segment_index] in ('(r)', 'server'): segment_index += 1 # Check if the version has a suffix. suffix_segment_index = segment_index + 1 if (suffix_segment_index < number_of_segments and product_lower_case[suffix_segment_index] == 'r2'): return 'Windows {0:s} R2'.format(product[segment_index]) return 'Windows {0:s}'.format(product[segment_index]) return None
java
public void setSSECustomerKey(SSECustomerKey sseKey) { if (sseKey != null && this.sseAwsKeyManagementParams != null) { throw new IllegalArgumentException( "Either SSECustomerKey or SSEAwsKeyManagementParams must not be set at the same time."); } this.sseCustomerKey = sseKey; }
python
def find_asts(self, ast_root, name): ''' Finds an AST node with the given name and the entire subtree under it. A function borrowed from scottfrazer. Thank you Scott Frazer! :param ast_root: The WDL AST. The whole thing generally, but really any portion that you wish to search. :param name: The name of the subtree you're looking for, like "Task". :return: nodes representing the AST subtrees matching the "name" given. ''' nodes = [] if isinstance(ast_root, wdl_parser.AstList): for node in ast_root: nodes.extend(self.find_asts(node, name)) elif isinstance(ast_root, wdl_parser.Ast): if ast_root.name == name: nodes.append(ast_root) for attr_name, attr in ast_root.attributes.items(): nodes.extend(self.find_asts(attr, name)) return nodes
python
def peek(self, default=None): '''Returns `default` is there is no subsequent item''' try: result = self.pointer.next() # immediately push it back onto the front of the iterable self.pointer = itertools.chain([result], self.pointer) return result except StopIteration: # nothing to put back; iterating doesn't change anything past the end return default
python
def normalizeGlyphHeight(value): """ Normalizes glyph height. * **value** must be a :ref:`type-int-float`. * Returned value is the same type as the input value. """ if not isinstance(value, (int, float)): raise TypeError("Glyph height must be an :ref:`type-int-float`, not " "%s." % type(value).__name__) return value
java
public final void setUtc(final boolean utc) { if (getDate() != null && (getDate() instanceof DateTime)) { ((DateTime) getDate()).setUtc(utc); } getParameters().remove(getParameter(Parameter.TZID)); }
java
protected <T extends Annotation> T extractPropertyAnnotation(Method writeMethod, Method readMethod, Class<T> annotationClass) { T parameterDescription = writeMethod.getAnnotation(annotationClass); if (parameterDescription == null && readMethod != null) { parameterDescription = readMethod.getAnnotation(annotationClass); } return parameterDescription; }
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: _dict['languages'] = [x._to_dict() for x in self.languages] return _dict
java
public void enc_ndr_string ( String s ) { align(4); int i = this.index; int len = s.length(); Encdec.enc_uint32le(len + 1, this.buf, i); i += 4; Encdec.enc_uint32le(0, this.buf, i); i += 4; Encdec.enc_uint32le(len + 1, this.buf, i); i += 4; System.arraycopy(Strings.getUNIBytes(s), 0, this.buf, i, len * 2); i += len * 2; this.buf[ i++ ] = (byte) '\0'; this.buf[ i++ ] = (byte) '\0'; advance(i - this.index); }
python
def plot_eighh(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the maximum absolute value eigenvalue of the horizontal tensor. Usage ----- x.plot_eighh([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientation, cb_label, show, fname]) Parameters ---------- tick_interval : list or tuple, optional, default = [30, 30] Intervals to use when plotting the x and y ticks. If set to None, ticks will not be plotted. xlabel : str, optional, default = 'longitude' Label for the longitude axis. ylabel : str, optional, default = 'latitude' Label for the latitude axis. ax : matplotlib axes object, optional, default = None A single matplotlib axes object where the plot will appear. colorbar : bool, optional, default = True If True, plot a colorbar. cb_orientation : str, optional, default = 'vertical' Orientation of the colorbar: either 'vertical' or 'horizontal'. cb_label : str, optional, default = '$\lambda_{hh}$' Text label for the colorbar. show : bool, optional, default = True If True, plot the image to the screen. fname : str, optional, default = None If present, and if axes is not specified, save the image to the specified file. kwargs : optional Keyword arguements that will be sent to the SHGrid.plot() and plt.imshow() methods. """ if cb_label is None: cb_label = self._eighh_label if self.eighh is None: self.compute_eigh() if ax is None: fig, axes = self.eighh.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, show=False, **kwargs) if show: fig.show() if fname is not None: fig.savefig(fname) return fig, axes else: self.eighh.plot(colorbar=colorbar, cb_orientation=cb_orientation, cb_label=cb_label, ax=ax, **kwargs)
python
def last_written_time(self): """dfdatetime.DateTimeValues: last written time.""" timestamp = self._pyregf_key.get_last_written_time_as_integer() if timestamp == 0: return dfdatetime_semantic_time.SemanticTime('Not set') return dfdatetime_filetime.Filetime(timestamp=timestamp)
python
def iterate_nodes(self, key, distinct=True): """hash_ring compatibility implementation. Given a string key it returns the nodes as a generator that can hold the key. The generator iterates one time through the ring starting at the correct position. if `distinct` is set, then the nodes returned will be unique, i.e. no virtual copies will be returned. """ if not self.runtime._ring: yield None else: for node in self.range(key, unique=distinct): yield node['nodename']
python
def check_assertions(self, checklist, all=False): """Check a set of assertions @param all boolean if False, stop at first failure @return: False if any assertion fails. """ assert isinstance(checklist, dict) and 'checks' in checklist retval = None retlist = [] for assertion in checklist['checks']: retval = self.check_assertion(**assertion) retlist.append(retval) if not retval.success and not all: print "Error message:", retval[3] return retlist return retlist
python
def invalidate_m2m_cache(sender, instance, model, **kwargs): """ Signal receiver for models to invalidate model cache for many-to-many relationship. Parameters ~~~~~~~~~~ sender The model class instance The instance whose many-to-many relation is updated. model The class of the objects that are added to, removed from or cleared from the relation. """ logger.debug('Received m2m_changed signals from sender {0}'.format(sender)) update_model_cache(instance._meta.db_table) update_model_cache(model._meta.db_table)
java
public void addMasterListeners() { super.addMasterListeners(); this.getField(FileHdr.FILE_NAME).addListener(new MoveOnChangeHandler(this.getField(FileHdr.FILE_MAIN_FILENAME), null, false, true)); }
java
public void setContentTypeEngine(ContentTypeEngine engine) { String contentType = engine.getContentType(); String suffix = StringUtils.removeStart(contentType.substring(contentType.lastIndexOf('/') + 1), "x-"); engines.put(engine.getContentType(), engine); suffixes.put(suffix.toLowerCase(), engine); log.debug("'{}' content engine is '{}'", engine.getContentType(), engine.getClass().getName()); }
python
def __check_index(self, start_date, end_date): """check if maybe index needs rebuilding in the time span""" index_query = """SELECT id FROM facts WHERE (end_time >= ? OR end_time IS NULL) AND start_time <= ? AND id not in(select id from fact_index)""" rebuild_ids = ",".join([str(res[0]) for res in self.fetchall(index_query, (start_date, end_date))]) if rebuild_ids: query = """ SELECT a.id AS id, a.start_time AS start_time, a.end_time AS end_time, a.description as description, b.name AS name, b.id as activity_id, coalesce(c.name, ?) as category, e.name as tag FROM facts a LEFT JOIN activities b ON a.activity_id = b.id LEFT JOIN categories c ON b.category_id = c.id LEFT JOIN fact_tags d ON d.fact_id = a.id LEFT JOIN tags e ON e.id = d.tag_id WHERE a.id in (%s) ORDER BY a.id """ % rebuild_ids facts = self.__group_tags(self.fetchall(query, (self._unsorted_localized, ))) insert = """INSERT INTO fact_index (id, name, category, description, tag) VALUES (?, ?, ?, ?, ?)""" params = [(fact['id'], fact['name'], fact['category'], fact['description'], " ".join(fact['tags'])) for fact in facts] self.executemany(insert, params)
java
public static String getStaticResourceContext(String opencmsContext, String opencmsVersion) { return opencmsContext + STATIC_RESOURCE_PREFIX + "/v" + opencmsVersion.hashCode() + "v"; }
java
public static boolean isDirectoryPath(URI path) { return (path != null) && path.toString().endsWith(GoogleCloudStorage.PATH_DELIMITER); }
python
async def keep_alive(self, command): """ Periodically send a keep alive message to the Arduino. Frequency of keep alive transmission is calculated as follows: keep_alive_sent = period - (period * margin) :param command: {"method": "keep_alive", "params": [PERIOD, MARGIN]} Period is time period between keepalives. Range is 0-10 seconds. 0 disables the keepalive mechanism. Margin is a safety margin to assure keepalives are sent before period expires. Range is 0.1 to 0.9 :returns: No return value """ period = int(command[0]) margin = int(command[1]) await self.core.keep_alive(period, margin)
python
def _draw_visible_area(self, painter): """ Draw the visible area. This method does not take folded blocks into account. :type painter: QtGui.QPainter """ if self.editor.visible_blocks: start = self.editor.visible_blocks[0][-1] end = self.editor.visible_blocks[-1][-1] rect = QtCore.QRect() rect.setX(0) rect.setY(start.blockNumber() * self.get_marker_height()) rect.setWidth(self.sizeHint().width()) rect.setBottom(end.blockNumber() * self.get_marker_height()) if self.editor.background.lightness() < 128: c = self.editor.background.darker(150) else: c = self.editor.background.darker(110) c.setAlpha(128) painter.fillRect(rect, c)
java
void parse( CharSequence text, ParseLog status, AttributeQuery attributes, ParsedEntity<?> parsedResult, boolean quickPath ) { AttributeQuery aq = (quickPath ? this.fullAttrs : this.getQuery(attributes)); if ( (this.padLeft == 0) && (this.padRight == 0) ) { // Optimierung this.doParse(text, status, aq, parsedResult, quickPath); return; } boolean strict = this.isStrict(aq); char padChar = this.getPadChar(aq); int start = status.getPosition(); int endPos = text.length(); int index = start; // linke Füllzeichen konsumieren while ( (index < endPos) && (text.charAt(index) == padChar) ) { index++; } int leftPadCount = index - start; if (strict && (leftPadCount > this.padLeft)) { status.setError(start, this.padExceeded()); return; } // Eigentliche Parser-Routine status.setPosition(index); this.doParse(text, status, aq, parsedResult, quickPath); if (status.isError()) { return; } index = status.getPosition(); int width = index - start - leftPadCount; if ( strict && (this.padLeft > 0) && ((width + leftPadCount) != this.padLeft) ) { status.setError(start, this.padMismatched()); return; } // rechte Füllzeichen konsumieren int rightPadCount = 0; while ( (index < endPos) && (!strict || (width + rightPadCount < this.padRight)) && (text.charAt(index) == padChar) ) { index++; rightPadCount++; } if ( strict && (this.padRight > 0) && ((width + rightPadCount) != this.padRight) ) { status.setError(index - rightPadCount, this.padMismatched()); return; } status.setPosition(index); }
java
@Override public void setup(AbstractInvokable parent) { @SuppressWarnings("unchecked") final GenericCollectorMap<IT, OT> mapper = RegularPactTask.instantiateUserCode(this.config, userCodeClassLoader, GenericCollectorMap.class); this.mapper = mapper; mapper.setRuntimeContext(getUdfRuntimeContext()); }
python
def rmtree_errorhandler(func, path, exc_info): """On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.""" # if file type currently read only if os.stat(path).st_mode & stat.S_IREAD: # convert to read/write os.chmod(path, stat.S_IWRITE) # use the original function to repeat the operation func(path) return else: raise
java
public void setTCPBufferSize(int size) throws IOException, ServerException { if (size <= 0) { throw new IllegalArgumentException("size <= 0"); } try { boolean succeeded = false; String sizeString = Integer.toString(size); FeatureList feat = getFeatureList(); if (feat.contains(FeatureList.SBUF)) { succeeded = tryExecutingCommand( new Command("SBUF", sizeString)); } if (!succeeded) { succeeded = tryExecutingCommand( new Command("SITE BUFSIZE", sizeString)); } if (!succeeded) { succeeded = tryExecutingTwoCommands(new Command("SITE RETRBUFSIZE", sizeString), new Command("SITE STORBUFSIZE", sizeString)); } if (!succeeded) { succeeded = tryExecutingTwoCommands(new Command("SITE RBUFSZ", sizeString), new Command("SITE SBUFSZ", sizeString)); } if (!succeeded) { succeeded = tryExecutingTwoCommands(new Command("SITE RBUFSIZ", sizeString), new Command("SITE SBUFSIZ", sizeString)); } if (succeeded) { this.gSession.TCPBufferSize = size; } else { throw new ServerException(ServerException.SERVER_REFUSED, "Server refused setting TCP buffer size with any of the known commands."); } } catch (FTPReplyParseException rpe) { throw ServerException.embedFTPReplyParseException(rpe); } }
java
@Override public boolean requeueSilent(IQueueMessage<ID, DATA> msg) { try { return putToQueue(msg.clone(), true); } catch (RocksDBException e) { throw new QueueException(e); } }
java
private static void checkFinalImageBounds(Bitmap source, int x, int y, int width, int height) { Preconditions.checkArgument( x + width <= source.getWidth(), "x + width must be <= bitmap.width()"); Preconditions.checkArgument( y + height <= source.getHeight(), "y + height must be <= bitmap.height()"); }
python
def org_invite(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /org-xxxx/invite API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2Finvite """ return DXHTTPRequest('/%s/invite' % object_id, input_params, always_retry=always_retry, **kwargs)
java
public static String matchListPrefix( String objectNamePrefix, String delimiter, String objectName) { Preconditions.checkArgument(!Strings.isNullOrEmpty(objectName), "objectName must not be null or empty, had args %s/%s/%s: ", objectNamePrefix, delimiter, objectName); // The suffix that we'll use to check for the delimiter is just the whole name if no prefix // was supplied. String suffix = objectName; int suffixIndex = 0; if (objectNamePrefix != null) { // The underlying GCS API does return objectName when it equals the prefix, but our // GoogleCloudStorage wrapper filters this case if the objectName also ends with // PATH_DELIMITER. if (!objectName.startsWith(objectNamePrefix) || (objectName.equals(objectNamePrefix) && objectNamePrefix.endsWith(PATH_DELIMITER))) { return null; } else { suffixIndex = objectNamePrefix.length(); suffix = objectName.substring(suffixIndex); } } if (!Strings.isNullOrEmpty(delimiter) && suffix.contains(delimiter)) { // Return the full prefix and suffix up through first occurrence of delimiter after // the prefix, inclusive of the delimiter. objectName = objectName.substring( 0, objectName.indexOf(delimiter, suffixIndex) + delimiter.length()); } return objectName; }
python
def match_string(pattern, search_string): ''' Match a pattern in a string ''' rexobj = REX(pattern, None) rexpatstr = reformat_pattern(pattern) #print "rexpatstr: ", rexpatstr rexpat = re.compile(rexpatstr) rexobj.rex_patternstr = rexpatstr rexobj.rex_pattern = rexpat line_count = 1 for line in search_string.splitlines(): line = line.strip() mobj = rexpat.match(line) if mobj: populate_resobj(rexobj, mobj, line_count) line_count += 1 return rexobj
python
def on_episode_begin(self, episode, logs): """ Reset environment variables at beginning of each episode """ self.episode_start[episode] = timeit.default_timer() self.observations[episode] = [] self.rewards[episode] = [] self.actions[episode] = [] self.metrics[episode] = []
python
def stats(self, symbol): """ curl https://api.bitfinex.com/v1/stats/btcusd [ {"period":1,"volume":"7410.27250155"}, {"period":7,"volume":"52251.37118006"}, {"period":30,"volume":"464505.07753251"} ] """ data = self._get(self.url_for(PATH_STATS, (symbol))) for period in data: for key, value in period.items(): if key == 'period': new_value = int(value) elif key == 'volume': new_value = float(value) period[key] = new_value return data
python
def browse( plugins, parent = None, default = None ): """ Prompts the user to browse the wizards based on the inputed plugins \ allowing them to launch any particular wizard of choice. :param plugins | [<XWizardPlugin>, ..] parent | <QWidget> default | <XWizardPlugin> || None :return <bool> success """ dlg = XWizardBrowserDialog( parent ) dlg.setPlugins(plugins) dlg.setCurrentPlugin(default) if ( dlg.exec_() ): return True return False
python
def get_bugs(*key_value): """Get list of bugs matching certain criteria. The conditions are defined by key value pairs. Possible keys are: * "package": bugs for the given package * "submitter": bugs from the submitter * "maint": bugs belonging to a maintainer * "src": bugs belonging to a source package * "severity": bugs with a certain severity * "status": can be either "done", "forwarded", or "open" * "tag": see http://www.debian.org/Bugs/Developer#tags for available tags * "owner": bugs which are assigned to `owner` * "bugs": takes single int or list of bugnumbers, filters the list according to given criteria * "correspondent": bugs where `correspondent` has sent a mail to Arguments --------- key_value : str Returns ------- bugs : list of ints the bugnumbers Examples -------- >>> get_bugs('package', 'gtk-qt-engine', 'severity', 'normal') [12345, 23456] """ # previous versions also accepted # get_bugs(['package', 'gtk-qt-engine', 'severity', 'normal']) # if key_value is a list in a one elemented tuple, remove the # wrapping list if len(key_value) == 1 and isinstance(key_value[0], list): key_value = tuple(key_value[0]) # pysimplesoap doesn't generate soap Arrays without using wsdl # I build body by hand, converting list to array and using standard # pysimplesoap marshalling for other types method_el = SimpleXMLElement('<get_bugs></get_bugs>') for arg_n, kv in enumerate(key_value): arg_name = 'arg' + str(arg_n) if isinstance(kv, (list, tuple)): _build_int_array_el(arg_name, method_el, kv) else: method_el.marshall(arg_name, kv) soap_client = _build_soap_client() reply = soap_client.call('get_bugs', method_el) items_el = reply('soapenc:Array') return [int(item_el) for item_el in items_el.children() or []]
python
def remove(self, param, author=None): """Remove by url or name""" if isinstance(param, SkillEntry): skill = param else: skill = self.find_skill(param, author) skill.remove() skills = [s for s in self.skills_data['skills'] if s['name'] != skill.name] self.skills_data['skills'] = skills return
python
def _do_post_text(tx): """ Try to find out what the variables mean: tx A structure containing more informations about paragraph ??? leading Height of lines ff 1/8 of the font size y0 The "baseline" postion ??? y 1/8 below the baseline """ xs = tx.XtraState leading = xs.style.leading autoLeading = xs.autoLeading f = xs.f if autoLeading == 'max': # leading = max(leading, f.fontSize) leading = max(leading, LEADING_FACTOR * f.fontSize) elif autoLeading == 'min': leading = LEADING_FACTOR * f.fontSize ff = 0.125 * f.fontSize y0 = xs.cur_y y = y0 - ff # Background for x1, x2, c, fs in xs.backgrounds: inlineFF = fs * 0.125 gap = inlineFF * 1.25 tx._canvas.setFillColor(c) tx._canvas.rect(x1, y - gap, x2 - x1, fs + 1, fill=1, stroke=0) xs.backgrounds = [] xs.background = 0 xs.backgroundColor = None xs.backgroundFontSize = None # Underline yUnderline = y0 - 1.5 * ff tx._canvas.setLineWidth(ff * 0.75) csc = None for x1, x2, c in xs.underlines: if c != csc: tx._canvas.setStrokeColor(c) csc = c tx._canvas.line(x1, yUnderline, x2, yUnderline) xs.underlines = [] xs.underline = 0 xs.underlineColor = None # Strike for x1, x2, c, fs in xs.strikes: inlineFF = fs * 0.125 ys = y0 + 2 * inlineFF if c != csc: tx._canvas.setStrokeColor(c) csc = c tx._canvas.setLineWidth(inlineFF * 0.75) tx._canvas.line(x1, ys, x2, ys) xs.strikes = [] xs.strike = 0 xs.strikeColor = None yl = y + leading for x1, x2, link, c in xs.links: # No automatic underlining for links, never! _doLink(tx, link, (x1, y, x2, yl)) xs.links = [] xs.link = None xs.linkColor = None xs.cur_y -= leading
java
public ListOutgoingCertificatesResult withOutgoingCertificates(OutgoingCertificate... outgoingCertificates) { if (this.outgoingCertificates == null) { setOutgoingCertificates(new java.util.ArrayList<OutgoingCertificate>(outgoingCertificates.length)); } for (OutgoingCertificate ele : outgoingCertificates) { this.outgoingCertificates.add(ele); } return this; }
python
def load(self, name, location='local'): """Load saved data from the cache directory.""" path = self._get_path(name, location, file_ext='.json') if op.exists(path): return _load_json(path) path = self._get_path(name, location, file_ext='.pkl') if op.exists(path): return _load_pickle(path) logger.debug("The file `%s` doesn't exist.", path) return {}
java
public DRUMSReader<Data> getReader() throws FileLockException, IOException { if (reader_instance != null && !reader_instance.filesAreOpened) { reader_instance.openFiles(); } else { reader_instance = new DRUMSReader<Data>(this); } return reader_instance; }
java
public void marshall(ListActionExecutionsRequest listActionExecutionsRequest, ProtocolMarshaller protocolMarshaller) { if (listActionExecutionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listActionExecutionsRequest.getPipelineName(), PIPELINENAME_BINDING); protocolMarshaller.marshall(listActionExecutionsRequest.getFilter(), FILTER_BINDING); protocolMarshaller.marshall(listActionExecutionsRequest.getMaxResults(), MAXRESULTS_BINDING); protocolMarshaller.marshall(listActionExecutionsRequest.getNextToken(), NEXTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
python
def export(self, name, columns, points): """Export the stats to the Statsd server.""" for i in range(len(columns)): if not isinstance(points[i], Number): continue stat_name = '{}.{}.{}'.format(self.prefix, name, columns[i]) stat_value = points[i] tags = self.parse_tags(self.tags) try: self.client.send(stat_name, stat_value, **tags) except Exception as e: logger.error("Can not export stats %s to OpenTSDB (%s)" % (name, e)) logger.debug("Export {} stats to OpenTSDB".format(name))
java
public Charset getCharset() { String enc = getEncoding(); if (enc == null) { return Charset.defaultCharset(); } else { return Charset.forName(enc); } }
python
def getEditPerson(self, name): """ Get an L{EditPersonView} for editing the person named C{name}. @param name: A person name. @type name: C{unicode} @rtype: L{EditPersonView} """ view = EditPersonView(self.organizer.personByName(name)) view.setFragmentParent(self) return view
java
public static InputStream wrap(InputStream is, String task) { ProgressBarBuilder pbb = new ProgressBarBuilder().setTaskName(task).setInitialMax(Util.getInputStreamSize(is)); return wrap(is, pbb); }
java
public static String unescape(String oldstr) { /* * In contrast to fixing Java's broken regex charclasses, * this one need be no bigger, as unescaping shrinks the string * here, where in the other one, it grows it. */ StringBuilder newstr = new StringBuilder(oldstr.length()); boolean saw_backslash = false; for (int i = 0; i < oldstr.length(); i++) { int cp = oldstr.codePointAt(i); if (oldstr.codePointAt(i) > Character.MAX_VALUE) { i++; /* WE HATES UTF-16! WE HATES IT FOREVERSES!!! */ } if (!saw_backslash) { if (cp == '\\') { saw_backslash = true; } else { newstr.append(Character.toChars(cp)); } continue; /* switch */ } if (cp == '\\') { saw_backslash = false; newstr.append('\\'); newstr.append('\\'); continue; /* switch */ } switch (cp) { case 'r': newstr.append('\r'); break; /* switch */ case 'n': newstr.append('\n'); break; /* switch */ case 'f': newstr.append('\f'); break; /* switch */ /* PASS a \b THROUGH!! */ case 'b': newstr.append("\\b"); break; /* switch */ case 't': newstr.append('\t'); break; /* switch */ case 'a': newstr.append('\007'); break; /* switch */ case 'e': newstr.append('\033'); break; /* switch */ /* * A "control" character is what you get when you xor its * codepoint with '@'==64. This only makes sense for ASCII, * and may not yield a "control" character after all. * * Strange but true: "\c{" is ";", "\c}" is "=", etc. */ case 'c': { if (++i == oldstr.length()) { die("trailing \\c"); } cp = oldstr.codePointAt(i); /* * don't need to grok surrogates, as next line blows them up */ if (cp > 0x7f) { die("expected ASCII after \\c"); } newstr.append(Character.toChars(cp ^ 64)); break; /* switch */ } case '8': case '9': die("illegal octal digit"); /* NOTREACHED */ /* * may be 0 to 2 octal digits following this one * so back up one for fallthrough to next case; * unread this digit and fall through to next case. */ case '1': case '2': case '3': case '4': case '5': case '6': case '7': --i; /* FALLTHROUGH */ /* * Can have 0, 1, or 2 octal digits following a 0 * this permits larger values than octal 377, up to * octal 777. */ case '0': { if (i + 1 == oldstr.length()) { /* found \0 at end of string */ newstr.append(Character.toChars(0)); break; /* switch */ } i++; int digits = 0; int j; for (j = 0; j <= 2; j++) { if (i + j == oldstr.length()) { break; /* for */ } /* safe because will unread surrogate */ int ch = oldstr.charAt(i + j); if (ch < '0' || ch > '7') { break; /* for */ } digits++; } if (digits == 0) { --i; newstr.append('\0'); break; /* switch */ } int value = 0; try { value = Integer.parseInt( oldstr.substring(i, i + digits), 8); } catch (NumberFormatException nfe) { die("invalid octal value for \\0 escape"); } newstr.append(Character.toChars(value)); i += digits - 1; break; /* switch */ } /* end case '0' */ case 'x': { if (i + 2 > oldstr.length()) { die("string too short for \\x escape"); } i++; boolean saw_brace = false; if (oldstr.charAt(i) == '{') { /* ^^^^^^ ok to ignore surrogates here */ i++; saw_brace = true; } int j; for (j = 0; j < 8; j++) { if (!saw_brace && j == 2) { break; // for } /* * ASCII test also catches surrogates */ int ch = oldstr.charAt(i + j); if (ch > 127) { die("illegal non-ASCII hex digit in \\x escape"); } if (saw_brace && ch == '}') { break; /* for */ } if (!((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'))) { die(String.format("illegal hex digit #%d '%c' in \\x", ch, ch)); } } if (j == 0) { die("empty braces in \\x{} escape"); } int value = 0; try { value = Integer.parseInt(oldstr.substring(i, i + j), 16); } catch (NumberFormatException nfe) { die("invalid hex value for \\x escape"); } newstr.append(Character.toChars(value)); if (saw_brace) { j++; } i += j - 1; break; /* switch */ } case 'u': { if (i + 4 > oldstr.length()) { die("string too short for \\u escape"); } i++; int j; for (j = 0; j < 4; j++) { /* this also handles the surrogate issue */ if (oldstr.charAt(i + j) > 127) { die("illegal non-ASCII hex digit in \\u escape"); } } int value = 0; try { value = Integer.parseInt(oldstr.substring(i, i + j), 16); } catch (NumberFormatException nfe) { die("invalid hex value for \\u escape"); } newstr.append(Character.toChars(value)); i += j - 1; break; /* switch */ } case 'U': { if (i + 8 > oldstr.length()) { die("string too short for \\U escape"); } i++; int j; for (j = 0; j < 8; j++) { /* this also handles the surrogate issue */ if (oldstr.charAt(i + j) > 127) { die("illegal non-ASCII hex digit in \\U escape"); } } int value = 0; try { value = Integer.parseInt(oldstr.substring(i, i + j), 16); } catch (NumberFormatException nfe) { die("invalid hex value for \\U escape"); } newstr.append(Character.toChars(value)); i += j - 1; break; /* switch */ } default: newstr.append('\\'); newstr.append(Character.toChars(cp)); /* * say(String.format( * "DEFAULT unrecognized escape %c passed through", * cp)); */ break; /* switch */ } saw_backslash = false; } /* weird to leave one at the end */ if (saw_backslash) { newstr.append('\\'); } return newstr.toString(); }
python
def r2_score(pred:Tensor, targ:Tensor)->Rank0Tensor: "R2 score (coefficient of determination) between `pred` and `targ`." pred,targ = flatten_check(pred,targ) u = torch.sum((targ - pred) ** 2) d = torch.sum((targ - targ.mean()) ** 2) return 1 - u / d
java
private static int getPreviousPageOffset(final int offset, final int limit) { return hasFullPreviousPage(offset, limit) ? getPreviousFullPageOffset(offset, limit) : getFirstPageOffset(); }
java
public PreferredValueMakersRegistry addFieldOrPropertyMaker(Class ownerType, String propertyName, Maker<?> maker) { Preconditions.checkNotNull(ownerType); Preconditions.checkNotNull(propertyName); makers.put(Matchers.equalTo(String.format(Settable.FULL_NAME_FORMAT, ownerType.getName(), propertyName)), maker); return this; }
python
def get_check_threads(self): """Return iterator of checker threads.""" for t in self.threads: name = t.getName() if name.startswith("CheckThread-"): yield name
python
def _setup_file_hierarchy_limit( self, files_count_limit, files_size_limit, temp_dir, cgroups, pid_to_kill): """Start thread that enforces any file-hiearchy limits.""" if files_count_limit is not None or files_size_limit is not None: file_hierarchy_limit_thread = FileHierarchyLimitThread( self._get_result_files_base(temp_dir), files_count_limit=files_count_limit, files_size_limit=files_size_limit, cgroups=cgroups, pid_to_kill=pid_to_kill, callbackFn=self._set_termination_reason, kill_process_fn=self._kill_process) file_hierarchy_limit_thread.start() return file_hierarchy_limit_thread return None
java
private boolean gatherHomePageEvidence(Dependency dependency, EvidenceType type, Pattern pattern, String source, String name, String contents) { final Matcher matcher = pattern.matcher(contents); boolean found = false; if (matcher.find()) { final String url = matcher.group(4); if (UrlStringUtils.isUrl(url)) { found = true; dependency.addEvidence(type, source, name, url, Confidence.MEDIUM); } } return found; }
java
public static Map<String, Field> getDeepDeclaredFieldMap(Class c) { Map<String, Field> fieldMap = new HashMap<>(); Collection<Field> fields = getDeepDeclaredFields(c); for (Field field : fields) { String fieldName = field.getName(); if (fieldMap.containsKey(fieldName)) { // Can happen when parent and child class both have private field with same name fieldMap.put(field.getDeclaringClass().getName() + '.' + fieldName, field); } else { fieldMap.put(fieldName, field); } } return fieldMap; }
python
def add_to_following(self, following): """ :calls: `PUT /user/following/:user <http://developer.github.com/v3/users/followers>`_ :param following: :class:`github.NamedUser.NamedUser` :rtype: None """ assert isinstance(following, github.NamedUser.NamedUser), following headers, data = self._requester.requestJsonAndCheck( "PUT", "/user/following/" + following._identity )
java
protected int getPopupHeight() { if (m_popup.isShowing()) { return m_popup.getOffsetHeight(); } else { Element el = CmsDomUtil.clone(m_popup.getElement()); RootPanel.getBodyElement().appendChild(el); el.getStyle().setProperty("position", "absolute"); int height = el.getOffsetHeight(); el.removeFromParent(); return height; } }
python
def presets(self, presets, opt): """Will create representational objects for any preset (push) based AppRole Secrets.""" for preset in presets: secret_obj = dict(preset) secret_obj['role_name'] = self.app_name self.secret_ids.append(AppRoleSecret(secret_obj, opt))
java
protected void writeCombiner( TupleCombiner combiner) { writer_ .element( COMBINE_TAG) .attribute( TUPLES_ATR, String.valueOf( combiner.getTupleSize())) .content( () -> { Arrays.stream( combiner.getIncluded()) .sorted() .forEach( this::writeIncluded); Arrays.stream( combiner.getExcluded()) .sorted() .forEach( this::writeExcluded); toStream( combiner.getOnceTuples()).forEach( this::writeOnceTuple); }) .write(); }