language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def on_for_seconds(self, steering, speed, seconds, brake=True, block=True): """ Rotate the motors according to the provided ``steering`` for ``seconds``. """ (left_speed, right_speed) = self.get_speed_steering(steering, speed) MoveTank.on_for_seconds(self, SpeedNativeUnits(left_speed), SpeedNativeUnits(right_speed), seconds, brake, block)
python
def parse_line(line: str, char_index=0) -> Tuple[ListingType, str]: """Parse FTP directory listing into (type, filename).""" entry_name = str.rpartition(line, ' ')[-1] entry_type = LISTING_FLAG_MAP.get(line[char_index], ListingType.other) return entry_type, entry_name
python
def status_raw(name=None, user=None, conf_file=None, bin_env=None): ''' Display the raw output of status user user to run supervisorctl as conf_file path to supervisord config file bin_env path to supervisorctl bin or path to virtualenv with supervisor installed CLI Example: .. code-block:: bash salt '*' supervisord.status_raw ''' ret = __salt__['cmd.run_all']( _ctl_cmd('status', name, conf_file, bin_env), runas=user, python_shell=False, ) return _get_return(ret)
python
def restore_gc_state(): """ Restore the garbage collector state on leaving the with block. """ old_isenabled = gc.isenabled() old_flags = gc.get_debug() try: yield finally: gc.set_debug(old_flags) (gc.enable if old_isenabled else gc.disable)()
java
private String getStringValue(Object o) { if (o instanceof String) { return (String) o; } else if (o instanceof XmlNodeArray) { XmlNodeArray array = (XmlNodeArray) o; switch (array.size()) { case 0: return null; case 1: { return getStringValue(array.get(0)); } default: return getStringValue(array); } } else if (o instanceof XmlNode) { return getStringValue((XmlNode) o); } else if (o != null) { return o.toString(); } return null; }
python
def compute_schema(schema_cls, default_kwargs, qs, include): """Compute a schema around compound documents and sparse fieldsets :param Schema schema_cls: the schema class :param dict default_kwargs: the schema default kwargs :param QueryStringManager qs: qs :param list include: the relation field to include data from :return Schema schema: the schema computed """ # manage include_data parameter of the schema schema_kwargs = default_kwargs schema_kwargs['include_data'] = tuple() # collect sub-related_includes related_includes = {} if include: for include_path in include: field = include_path.split('.')[0] if field not in schema_cls._declared_fields: raise InvalidInclude("{} has no attribute {}".format(schema_cls.__name__, field)) elif not isinstance(schema_cls._declared_fields[field], Relationship): raise InvalidInclude("{} is not a relationship attribute of {}".format(field, schema_cls.__name__)) schema_kwargs['include_data'] += (field, ) if field not in related_includes: related_includes[field] = [] if '.' in include_path: related_includes[field] += ['.'.join(include_path.split('.')[1:])] # make sure id field is in only parameter unless marshamllow will raise an Exception if schema_kwargs.get('only') is not None and 'id' not in schema_kwargs['only']: schema_kwargs['only'] += ('id',) # create base schema instance schema = schema_cls(**schema_kwargs) # manage sparse fieldsets if schema.opts.type_ in qs.fields: tmp_only = set(schema.declared_fields.keys()) & set(qs.fields[schema.opts.type_]) if schema.only: tmp_only &= set(schema.only) schema.only = tuple(tmp_only) # make sure again that id field is in only parameter unless marshamllow will raise an Exception if schema.only is not None and 'id' not in schema.only: schema.only += ('id',) # manage compound documents if include: for include_path in include: field = include_path.split('.')[0] relation_field = schema.declared_fields[field] related_schema_cls = schema.declared_fields[field].__dict__['_Relationship__schema'] related_schema_kwargs = {} if 'context' in default_kwargs: related_schema_kwargs['context'] = default_kwargs['context'] if isinstance(related_schema_cls, SchemaABC): related_schema_kwargs['many'] = related_schema_cls.many related_schema_cls = related_schema_cls.__class__ if isinstance(related_schema_cls, str): related_schema_cls = class_registry.get_class(related_schema_cls) related_schema = compute_schema(related_schema_cls, related_schema_kwargs, qs, related_includes[field] or None) relation_field.__dict__['_Relationship__schema'] = related_schema return schema
java
public static void runWith( String[] args, Function<BenchmarkSettings, SmCodecBenchmarkState> benchmarkStateFactory) { BenchmarkSettings settings = BenchmarkSettings.from(args).durationUnit(TimeUnit.NANOSECONDS).build(); SmCodecBenchmarkState benchmarkState = benchmarkStateFactory.apply(settings); benchmarkState.runForSync( state -> { BenchmarkTimer timer = state.timer("timer"); BenchmarkMeter meter = state.meter("meter"); ServiceMessageCodec messageCodec = state.messageCodec(); Class<?> dataType = state.dataType(); return i -> { Context timeContext = timer.time(); ByteBuf dataBuffer = state.dataBuffer().retain(); ByteBuf headersBuffer = state.headersBuffer().retain(); ServiceMessage message = ServiceMessageCodec.decodeData( messageCodec.decode(dataBuffer, headersBuffer), dataType); timeContext.stop(); meter.mark(); return message; }; }); }
java
private static void simpleClassTypeSignature(Result sb, TypeMirror type) throws IOException { switch (type.getKind()) { case DECLARED: DeclaredType dt = (DeclaredType) type; TypeElement te = (TypeElement) dt.asElement(); nestedSimpleName(sb, te); typeArguments(sb, dt.getTypeArguments()); break; default: throw new UnsupportedOperationException(type.getKind()+" unsupported"); } }
python
def tags_to_versions(tags, config=None): """ take tags that might be prefixed with a keyword and return only the version part :param tags: an iterable of tags :param config: optional configuration object """ result = [] for tag in tags: tag = tag_to_version(tag, config=config) if tag: result.append(tag) return result
python
def located_error( original_error: Union[Exception, GraphQLError], nodes: Sequence["Node"], path: Sequence[Union[str, int]], ) -> GraphQLError: """Located GraphQL Error Given an arbitrary Error, presumably thrown while attempting to execute a GraphQL operation, produce a new GraphQLError aware of the location in the document responsible for the original Error. """ if original_error: # Note: this uses a brand-check to support GraphQL errors originating from # other contexts. try: if isinstance(original_error.path, list): # type: ignore return original_error # type: ignore except AttributeError: pass try: message = original_error.message # type: ignore except AttributeError: message = str(original_error) try: source = original_error.source # type: ignore except AttributeError: source = None try: positions = original_error.positions # type: ignore except AttributeError: positions = None try: nodes = original_error.nodes or nodes # type: ignore except AttributeError: pass return GraphQLError(message, nodes, source, positions, path, original_error)
java
public AC start(String taskName, Object... args) { final ProfilingTimerNode parent = current.get(); current.set(findOrCreateNode(String.format(taskName, args), parent)); return new AC() { @Override public void close() { // return to the parent that we had when this AC was created current.set(parent); // close all the elements in the subtree under current if (parent != null) stopAll(parent); } private void stopAll(ProfilingTimerNode current) { for (ProfilingTimerNode child : current.children.values()) { stopAll(child); child.stop(); } } }; }
python
def get_url_for_id(client_site_url, apikey, resource_id): """Return the URL for the given resource ID. Contacts the client site's API to get the URL for the ID and returns it. :raises CouldNotGetURLError: if getting the URL fails for any reason """ # TODO: Handle invalid responses from the client site. url = client_site_url + u"deadoralive/get_url_for_resource_id" params = {"resource_id": resource_id} response = requests.get(url, headers=dict(Authorization=apikey), params=params) if not response.ok: raise CouldNotGetURLError( u"Couldn't get URL for resource {id}: {code} {reason}".format( id=resource_id, code=response.status_code, reason=response.reason)) return response.json()
java
private Date addDays(final Date date, final int days) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, days); //minus number would decrement the days return cal.getTime(); }
java
public void execute(Task task) { LOG.info(String.format("Executing task %s", task.getTaskId())); this.taskExecutor.execute(new TrackingTask(task)); }
java
synchronized void resetAccounting(long newLastTime) { long interval = newLastTime - lastTime.getAndSet(newLastTime); if (interval == 0) { // nothing to do return; } if (logger.isDebugEnabled() && interval > checkInterval() << 1) { logger.debug("Acct schedule not ok: " + interval + " > 2*" + checkInterval() + " from " + name); } lastReadBytes = currentReadBytes.getAndSet(0); lastWrittenBytes = currentWrittenBytes.getAndSet(0); lastReadThroughput = lastReadBytes * 1000 / interval; // nb byte / checkInterval in ms * 1000 (1s) lastWriteThroughput = lastWrittenBytes * 1000 / interval; // nb byte / checkInterval in ms * 1000 (1s) realWriteThroughput = realWrittenBytes.getAndSet(0) * 1000 / interval; lastWritingTime = Math.max(lastWritingTime, writingTime); lastReadingTime = Math.max(lastReadingTime, readingTime); }
java
@Override public Request<DescribeVpcClassicLinkRequest> getDryRunRequest() { Request<DescribeVpcClassicLinkRequest> request = new DescribeVpcClassicLinkRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
python
def phase2radians(phasedata, v0): """ Convert phase in seconds to phase in radians Parameters ---------- phasedata: np.array Data array of phase in seconds v0: float Nominal oscillator frequency in Hz Returns ------- fi: phase data in radians """ fi = [2*np.pi*v0*xx for xx in phasedata] return fi
python
def short_repr(obj, noneAsNA=False): '''Return a short representation of obj for clarity.''' if obj is None: return 'unspecified' if noneAsNA else 'None' elif isinstance(obj, str) and len(obj) > 80: return '{}...{}'.format(obj[:60].replace('\n', '\\n'), obj[-20:].replace('\n', '\\n')) elif isinstance(obj, (str, int, float, bool)): return repr(obj) elif hasattr(obj, '__short_repr__'): return obj.__short_repr__() elif isinstance(obj, Sequence): # should be a list or tuple if len(obj) == 0: return '[]' elif len(obj) == 1: return f'{short_repr(obj[0])}' elif len(obj) == 2: return f'{short_repr(obj[0])}, {short_repr(obj[1])}' else: return f'{short_repr(obj[0])}, {short_repr(obj[1])}, ... ({len(obj)} items)' elif isinstance(obj, dict): if not obj: return '' elif len(obj) == 1: first_key = list(obj.keys())[0] return f'{short_repr(first_key)!r}:{short_repr(obj[first_key])!r}' else: first_key = list(obj.keys())[0] return f'{short_repr(first_key)}:{short_repr(obj[first_key])}, ... ({len(obj)} items)' elif isinstance(obj, KeysView): if not obj: return '' elif len(obj) == 1: return short_repr(next(iter(obj))) else: return f'{short_repr(next(iter(obj)))}, ... ({len(obj)} items)' #elif hasattr(obj, 'target_name'): # return obj.target_name() else: ret = str(obj) if len(ret) > 40: return f'{repr(obj)[:35]}...' else: return ret
python
def __set_bp(self, aThread): """ Sets this breakpoint in the debug registers. @type aThread: L{Thread} @param aThread: Thread object. """ if self.__slot is None: aThread.suspend() try: ctx = aThread.get_context(win32.CONTEXT_DEBUG_REGISTERS) self.__slot = DebugRegister.find_slot(ctx) if self.__slot is None: msg = "No available hardware breakpoint slots for thread ID %d" msg = msg % aThread.get_tid() raise RuntimeError(msg) DebugRegister.set_bp(ctx, self.__slot, self.get_address(), self.__trigger, self.__watch) aThread.set_context(ctx) finally: aThread.resume()
java
public void setEnabled(boolean enabled) { if (enabled && engine == null) { return; } if (this.enabled != enabled) { this.enabled = enabled; this.changed = true; } }
java
public static CurrencyUnit getCurrency(Locale locale, String... providers) { return Optional.ofNullable(MONETARY_CURRENCIES_SINGLETON_SPI()).orElseThrow( () -> new MonetaryException("No MonetaryCurrenciesSingletonSpi loaded, check your system setup.")) .getCurrency(locale, providers); }
java
public PagedList<ExperimentInner> listByWorkspaceNext(final String nextPageLink) { ServiceResponse<Page<ExperimentInner>> response = listByWorkspaceNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<ExperimentInner>(response.body()) { @Override public Page<ExperimentInner> nextPage(String nextPageLink) { return listByWorkspaceNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; }
python
def click_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT): """ This method clicks link text on a page """ # If using phantomjs, might need to extract and open the link directly if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) if self.browser == 'phantomjs': if self.is_link_text_visible(link_text): element = self.wait_for_link_text_visible( link_text, timeout=timeout) element.click() return self.open(self.__get_href_from_link_text(link_text)) return if not self.is_link_text_present(link_text): self.wait_for_link_text_present(link_text, timeout=timeout) pre_action_url = self.get_current_url() try: element = self.wait_for_link_text_visible( link_text, timeout=0.2) self.__demo_mode_highlight_if_active(link_text, by=By.LINK_TEXT) try: element.click() except (StaleElementReferenceException, ENI_Exception): self.wait_for_ready_state_complete() time.sleep(0.05) element = self.wait_for_link_text_visible( link_text, timeout=timeout) element.click() except Exception: found_css = False text_id = self.get_link_attribute(link_text, "id", False) if text_id: link_css = '[id="%s"]' % link_text found_css = True if not found_css: href = self.__get_href_from_link_text(link_text, False) if href: if href.startswith('/') or page_utils.is_valid_url(href): link_css = '[href="%s"]' % href found_css = True if not found_css: ngclick = self.get_link_attribute(link_text, "ng-click", False) if ngclick: link_css = '[ng-click="%s"]' % ngclick found_css = True if not found_css: onclick = self.get_link_attribute(link_text, "onclick", False) if onclick: link_css = '[onclick="%s"]' % onclick found_css = True success = False if found_css: if self.is_element_visible(link_css): self.click(link_css) success = True else: # The link text might be hidden under a dropdown menu success = self.__click_dropdown_link_text( link_text, link_css) if not success: element = self.wait_for_link_text_visible( link_text, timeout=settings.MINI_TIMEOUT) element.click() if settings.WAIT_FOR_RSC_ON_CLICKS: self.wait_for_ready_state_complete() if self.demo_mode: if self.driver.current_url != pre_action_url: self.__demo_mode_pause_if_active() else: self.__demo_mode_pause_if_active(tiny=True)
python
def _normalize_slice(self, index, pipe=None): """Given a :obj:`slice` *index*, return a 4-tuple ``(start, stop, step, fowrward)``. The first three items can be used with the ``range`` function to retrieve the values associated with the slice; the last item indicates the direction. """ if index.step == 0: raise ValueError pipe = self.redis if pipe is None else pipe len_self = self.__len__(pipe) step = index.step or 1 forward = step > 0 step = abs(step) if index.start is None: start = 0 if forward else len_self - 1 elif index.start < 0: start = max(len_self + index.start, 0) else: start = min(index.start, len_self) if index.stop is None: stop = len_self if forward else -1 elif index.stop < 0: stop = max(len_self + index.stop, 0) else: stop = min(index.stop, len_self) if not forward: start, stop = min(stop + 1, len_self), min(start + 1, len_self) return start, stop, step, forward, len_self
python
def _read_services(self): """ Read the control XML file and populate self.services with a list of services in the form of Service class instances. """ # The double slash in the XPath is deliberate, as services can be # listed in two places (Section 2.3 of uPNP device architecture v1.1) for node in self._findall('device//serviceList/service'): findtext = partial(node.findtext, namespaces=self._root_xml.nsmap) svc = Service( self, self._url_base, findtext('serviceType'), findtext('serviceId'), findtext('controlURL'), findtext('SCPDURL'), findtext('eventSubURL') ) self._log.debug( '%s: Service %r at %r', self.device_name, svc.service_type, svc.scpd_url) self.services.append(svc) self.service_map[svc.name] = svc
python
def from_csv(cls, path, header=0, sep=',', index_col=0, parse_dates=True, encoding=None, tupleize_cols=None, infer_datetime_format=False): """ Read CSV file. .. deprecated:: 0.21.0 Use :func:`read_csv` instead. It is preferable to use the more powerful :func:`read_csv` for most general purposes, but ``from_csv`` makes for an easy roundtrip to and from a file (the exact counterpart of ``to_csv``), especially with a DataFrame of time series data. This method only differs from the preferred :func:`read_csv` in some defaults: - `index_col` is ``0`` instead of ``None`` (take first column as index by default) - `parse_dates` is ``True`` instead of ``False`` (try parsing the index as datetime by default) So a ``pd.DataFrame.from_csv(path)`` can be replaced by ``pd.read_csv(path, index_col=0, parse_dates=True)``. Parameters ---------- path : string file path or file handle / StringIO header : int, default 0 Row to use as header (skip prior rows) sep : string, default ',' Field delimiter index_col : int or sequence, default 0 Column to use for index. If a sequence is given, a MultiIndex is used. Different default from read_table parse_dates : boolean, default True Parse dates. Different default from read_table tupleize_cols : boolean, default False write multi_index columns as a list of tuples (if True) or new (expanded format) if False) infer_datetime_format : boolean, default False If True and `parse_dates` is True for a column, try to infer the datetime format based on the first datetime string. If the format can be inferred, there often will be a large parsing speed-up. Returns ------- DataFrame See Also -------- read_csv """ warnings.warn("from_csv is deprecated. Please use read_csv(...) " "instead. Note that some of the default arguments are " "different, so please refer to the documentation " "for from_csv when changing your function calls", FutureWarning, stacklevel=2) from pandas.io.parsers import read_csv return read_csv(path, header=header, sep=sep, parse_dates=parse_dates, index_col=index_col, encoding=encoding, tupleize_cols=tupleize_cols, infer_datetime_format=infer_datetime_format)
python
def unpause(name): ''' Unpauses a container name Container name or ID **RETURN DATA** A dictionary will be returned, containing the following keys: - ``status`` - A dictionary showing the prior state of the container as well as the new state - ``result`` - A boolean noting whether or not the action was successful - ``comment`` - Only present if the container can not be unpaused CLI Example: .. code-block:: bash salt myminion docker.pause mycontainer ''' orig_state = state(name) if orig_state == 'stopped': return {'result': False, 'state': {'old': orig_state, 'new': orig_state}, 'comment': ('Container \'{0}\' is stopped, cannot unpause' .format(name))} return _change_state(name, 'unpause', 'running')
python
def _PrintEventLabelsCounter( self, event_labels_counter, session_identifier=None): """Prints the event labels counter. Args: event_labels_counter (collections.Counter): number of event tags per label. session_identifier (Optional[str]): session identifier. """ if not event_labels_counter: return title = 'Event tags generated per label' if session_identifier: title = '{0:s}: {1:s}'.format(title, session_identifier) table_view = views.ViewsFactory.GetTableView( self._views_format_type, column_names=['Label', 'Number of event tags'], title=title) for key, value in sorted(event_labels_counter.items()): if key == 'total': continue table_view.AddRow([key, value]) try: total = event_labels_counter['total'] except KeyError: total = 'N/A' table_view.AddRow(['Total', total]) table_view.Write(self._output_writer)
java
@Override public void quit(String reason) { if (!connected) { throw new NotConnectedException(); } Message quit = new Message(MessageType.QUIT, reason); ChannelFuture future = connection.send(quit); /* Wait for message to be sent and then close the underlying connection */ future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { connection.close(); } }); }
java
public void setAdditionalAction(PdfName actionType, PdfAction action) throws PdfException { if (!(actionType.equals(DOCUMENT_CLOSE) || actionType.equals(WILL_SAVE) || actionType.equals(DID_SAVE) || actionType.equals(WILL_PRINT) || actionType.equals(DID_PRINT))) { throw new PdfException("Invalid additional action type: " + actionType.toString()); } PdfDictionary aa = reader.getCatalog().getAsDict(PdfName.AA); if (aa == null) { if (action == null) return; aa = new PdfDictionary(); reader.getCatalog().put(PdfName.AA, aa); } markUsed(aa); if (action == null) aa.remove(actionType); else aa.put(actionType, action); }
java
public TableRef off(StorageEvent eventType, OnItemSnapshot onItemSnapshot) { Event ev = new Event(eventType, this.name, null, null, false, true, false, onItemSnapshot); context.removeEvent(ev); return this; }
java
private void closeResultSet (CodeBuilder b, LocalVariable rsVar, Label tryAfterRs) { Label contLabel = b.createLabel(); Label endFinallyLabel = b.createLabel().setLocation(); b.loadLocal(rsVar); b.invokeInterface(TypeDesc.forClass(ResultSet.class), "close", null, null); b.branch(contLabel); b.exceptionHandler(tryAfterRs, endFinallyLabel, null); b.loadLocal(rsVar); b.invokeInterface(TypeDesc.forClass(ResultSet.class), "close", null, null); b.throwObject(); contLabel.setLocation(); }
python
def save_to_file(self, filename_prefix): """Save the vocabulary to a file.""" # Wrap in single quotes to make it easier to see the full subword when # it has spaces and make it easier to search with ctrl+f. filename = self._filename(filename_prefix) lines = ["'%s'" % s for s in self._subwords] self._write_lines_to_file(filename, lines)
java
public static base_response update(nitro_service client, snmpgroup resource) throws Exception { snmpgroup updateresource = new snmpgroup(); updateresource.name = resource.name; updateresource.securitylevel = resource.securitylevel; updateresource.readviewname = resource.readviewname; return updateresource.update_resource(client); }
java
public static boolean deleteProperty(Scriptable obj, String name) { Scriptable base = getBase(obj, name); if (base == null) return true; base.delete(name); return !base.has(name, obj); }
java
public static Predicate<Map.Entry<Long, Boolean>> amongDeadHsids(final Set<Long> hsids) { return new Predicate<Map.Entry<Long,Boolean>>() { @Override public boolean apply(Entry<Long, Boolean> e) { return hsids.contains(e.getKey()) && e.getValue(); } }; }
python
def get_files(input_file): """ Initializes an index of files to generate, returns the base directory and index. """ file_index = {} base_dir = None if os.path.isfile(input_file): file_index[input_file] = None base_dir = os.path.dirname(input_file) elif os.path.isdir(input_file): base_dir = input_file for inf in glob.glob(input_file + s.SBP_EXTENSION): file_index[os.path.abspath(inf)] = None for inf in glob.glob(input_file + '/*'): base, index = get_files(os.path.abspath(inf)) z = file_index.copy() z.update(index) file_index = z return (base_dir, file_index)
java
private void error(PageException pe) { if (error == null) throw new PageRuntimeException(pe); try { pc = ThreadLocalPageContext.get(pc); error.call(pc, new Object[] { pe.getCatchBlock(pc.getConfig()) }, false); } catch (PageException e) {} }
java
public void project(double x, double y, double z, double[] out) { glu.gluProject(x, y, z, modelview, 0, projection, 0, viewp, 0, out, 0); }
java
public void writeFile(String resourceName, String exportpoint, byte[] content) { writeResource(resourceName, exportpoint, content); }
java
public Observable<ServiceResponseWithHeaders<Void, PoolStopResizeHeaders>> stopResizeWithServiceResponseAsync(String poolId, PoolStopResizeOptions poolStopResizeOptions) { if (this.client.batchUrl() == null) { throw new IllegalArgumentException("Parameter this.client.batchUrl() is required and cannot be null."); } if (poolId == null) { throw new IllegalArgumentException("Parameter poolId is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } Validator.validate(poolStopResizeOptions); Integer timeout = null; if (poolStopResizeOptions != null) { timeout = poolStopResizeOptions.timeout(); } UUID clientRequestId = null; if (poolStopResizeOptions != null) { clientRequestId = poolStopResizeOptions.clientRequestId(); } Boolean returnClientRequestId = null; if (poolStopResizeOptions != null) { returnClientRequestId = poolStopResizeOptions.returnClientRequestId(); } DateTime ocpDate = null; if (poolStopResizeOptions != null) { ocpDate = poolStopResizeOptions.ocpDate(); } String ifMatch = null; if (poolStopResizeOptions != null) { ifMatch = poolStopResizeOptions.ifMatch(); } String ifNoneMatch = null; if (poolStopResizeOptions != null) { ifNoneMatch = poolStopResizeOptions.ifNoneMatch(); } DateTime ifModifiedSince = null; if (poolStopResizeOptions != null) { ifModifiedSince = poolStopResizeOptions.ifModifiedSince(); } DateTime ifUnmodifiedSince = null; if (poolStopResizeOptions != null) { ifUnmodifiedSince = poolStopResizeOptions.ifUnmodifiedSince(); } String parameterizedHost = Joiner.on(", ").join("{batchUrl}", this.client.batchUrl()); DateTimeRfc1123 ocpDateConverted = null; if (ocpDate != null) { ocpDateConverted = new DateTimeRfc1123(ocpDate); } DateTimeRfc1123 ifModifiedSinceConverted = null; if (ifModifiedSince != null) { ifModifiedSinceConverted = new DateTimeRfc1123(ifModifiedSince); } DateTimeRfc1123 ifUnmodifiedSinceConverted = null; if (ifUnmodifiedSince != null) { ifUnmodifiedSinceConverted = new DateTimeRfc1123(ifUnmodifiedSince); } return service.stopResize(poolId, this.client.apiVersion(), this.client.acceptLanguage(), timeout, clientRequestId, returnClientRequestId, ocpDateConverted, ifMatch, ifNoneMatch, ifModifiedSinceConverted, ifUnmodifiedSinceConverted, parameterizedHost, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponseWithHeaders<Void, PoolStopResizeHeaders>>>() { @Override public Observable<ServiceResponseWithHeaders<Void, PoolStopResizeHeaders>> call(Response<ResponseBody> response) { try { ServiceResponseWithHeaders<Void, PoolStopResizeHeaders> clientResponse = stopResizeDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); }
python
def _convert_strls(self, data): """Convert columns to StrLs if either very large or in the convert_strl variable""" convert_cols = [ col for i, col in enumerate(data) if self.typlist[i] == 32768 or col in self._convert_strl] if convert_cols: ssw = StataStrLWriter(data, convert_cols) tab, new_data = ssw.generate_table() data = new_data self._strl_blob = ssw.generate_blob(tab) return data
java
@Override @SuppressWarnings("unchecked") @LogarithmicTime(amortized = true) public AddressableHeap.Handle<K, V> deleteMin() { if (size == 0) { throw new NoSuchElementException(); } Node<K, V> min; if (decreasePoolMinPos >= decreasePoolSize) { // decrease pool empty min = root; // cut all children, and combine them root = combine(cutChildren(root)); } else { Node<K, V> poolMin = decreasePool[decreasePoolMinPos]; int c; if (comparator == null) { c = ((Comparable<? super K>) root.key).compareTo(poolMin.key); } else { c = comparator.compare(root.key, poolMin.key); } if (c <= 0) { // root is smaller min = root; // cut children, combine Node<K, V> childrenTree = combine(cutChildren(root)); root = null; /* * Append to decrease pool without updating minimum as we are * going to consolidate anyway */ if (childrenTree != null) { addPool(childrenTree, false); } consolidate(); } else { // minimum in pool is smaller min = poolMin; // cut children, combine Node<K, V> childrenTree = combine(cutChildren(poolMin)); if (childrenTree != null) { // add to location of previous minimum and consolidate decreasePool[decreasePoolMinPos] = childrenTree; childrenTree.poolIndex = decreasePoolMinPos; } else { decreasePool[decreasePoolMinPos] = decreasePool[decreasePoolSize - 1]; decreasePool[decreasePoolMinPos].poolIndex = decreasePoolMinPos; decreasePool[decreasePoolSize - 1] = null; decreasePoolSize--; } poolMin.poolIndex = Node.NO_INDEX; consolidate(); } } size--; return min; }
java
public List<V> getAll(Object key) { List<V> res = map.get(key); if (res == null) { res = Collections.emptyList(); } return res; }
python
def chunks(data, size): """ Generator that splits the given data into chunks """ for i in range(0, len(data), size): yield data[i:i + size]
java
public static <T> T use(Class categoryClass, Closure<T> closure) { return THREAD_INFO.getInfo().use(categoryClass, closure); }
java
@BetaApi( "The surface for long-running operations is not stable yet and may change in the future.") public final OperationFuture<Instance, OperationMetadata> failoverInstanceAsync( InstanceName name, FailoverInstanceRequest.DataProtectionMode dataProtectionMode) { FailoverInstanceRequest request = FailoverInstanceRequest.newBuilder() .setName(name == null ? null : name.toString()) .setDataProtectionMode(dataProtectionMode) .build(); return failoverInstanceAsync(request); }
java
public static void setFileData(final File file, final byte[] fileData, final String contentType) throws FrameworkException, IOException { FileHelper.setFileData(file, fileData, contentType, true); }
java
public ZoneAwareLoadBalancer<T> buildDynamicServerListLoadBalancerWithUpdater() { if (serverListImpl == null) { serverListImpl = createServerListFromConfig(config, factory); } if (rule == null) { rule = createRuleFromConfig(config, factory); } if (serverListUpdater == null) { serverListUpdater = createServerListUpdaterFromConfig(config, factory); } return new ZoneAwareLoadBalancer<T>(config, rule, ping, serverListImpl, serverListFilter, serverListUpdater); }
python
def validator(node, rrn): ''' Colander validator that checks whether a given value is a valid Belgian national ID number . :raises colander.Invalid: If the value is no valid Belgian national ID number. ''' def _valid(_rrn): x = 97 - (int(_rrn[:-2]) - (int(_rrn[:-2]) // 97) * 97) return int(_rrn[-2:]) == x if len(rrn) != 11: raise colander.Invalid( node, 'Een rijksregisternummer moet 11 cijfers lang zijn.' ) elif not _valid(rrn): valid_rrn = False if rrn[:1] == '0' or rrn[:1] == '1': rrn = '2' + rrn valid_rrn = _valid(rrn) if not valid_rrn: raise colander.Invalid( node, 'Dit is geen correct rijksregisternummer.' )
python
def logout(self): """Explicit Abode logout.""" if self._token: header_data = { 'ABODE-API-KEY': self._token } self._session = requests.session() self._token = None self._panel = None self._user = None self._devices = None self._automations = None try: response = self._session.post( CONST.LOGOUT_URL, headers=header_data) response_object = json.loads(response.text) except OSError as exc: _LOGGER.warning("Caught exception during logout: %s", str(exc)) return False if response.status_code != 200: raise AbodeAuthenticationException( (response.status_code, response_object['message'])) _LOGGER.debug("Logout Response: %s", response.text) _LOGGER.info("Logout successful") return True
python
def create_launch_configuration(self, launch_config): """ Creates a new Launch Configuration. :type launch_config: :class:`boto.ec2.autoscale.launchconfig.LaunchConfiguration` :param launch_config: LaunchConfiguration object. """ params = {'ImageId': launch_config.image_id, 'LaunchConfigurationName': launch_config.name, 'InstanceType': launch_config.instance_type} if launch_config.key_name: params['KeyName'] = launch_config.key_name if launch_config.user_data: params['UserData'] = base64.b64encode(launch_config.user_data) if launch_config.kernel_id: params['KernelId'] = launch_config.kernel_id if launch_config.ramdisk_id: params['RamdiskId'] = launch_config.ramdisk_id if launch_config.block_device_mappings: self.build_list_params(params, launch_config.block_device_mappings, 'BlockDeviceMappings') if launch_config.security_groups: self.build_list_params(params, launch_config.security_groups, 'SecurityGroups') if launch_config.instance_monitoring: params['InstanceMonitoring.Enabled'] = 'true' return self.get_object('CreateLaunchConfiguration', params, Request, verb='POST')
python
def lset(self, name, index, value): """ Set the value in the list at index *idx* :param name: str the name of the redis key :param value: :param index: :return: Future() """ with self.pipe as pipe: value = self.valueparse.encode(value) return pipe.lset(self.redis_key(name), index, value)
java
private CmsContainerElementBean getModelReplacementElement( CmsContainerElementBean element, CmsContainerElementBean baseElement, boolean allowCopyModel) { boolean resetSettings = false; if (!baseElement.isCopyModel() && !baseElement.getFormatterId().equals(element.getFormatterId())) { I_CmsFormatterBean formatter = m_configData.getCachedFormatters().getFormatters().get( element.getFormatterId()); resetSettings = (formatter == null) || !formatter.getResourceTypeNames().contains( OpenCms.getResourceManager().getResourceType(baseElement.getResource()).getTypeName()); } Map<String, String> settings; if (resetSettings) { settings = new HashMap<String, String>(); for (String id : KEEP_SETTING_IDS) { if (element.getIndividualSettings().containsKey(id)) { settings.put(id, element.getIndividualSettings().get(id)); } } settings.put(CmsContainerElement.MODEL_GROUP_ID, element.getId().toString()); // transfer all other settings for (Entry<String, String> settingEntry : baseElement.getIndividualSettings().entrySet()) { if (!settings.containsKey(settingEntry.getKey())) { settings.put(settingEntry.getKey(), settingEntry.getValue()); } } } else { settings = new HashMap<String, String>(element.getIndividualSettings()); if (!(baseElement.isCopyModel() && allowCopyModel)) { // skip the model id in case of copy models settings.put(CmsContainerElement.MODEL_GROUP_ID, element.getId().toString()); if (allowCopyModel) { // transfer all other settings for (Entry<String, String> settingEntry : baseElement.getIndividualSettings().entrySet()) { if (!settings.containsKey(settingEntry.getKey())) { settings.put(settingEntry.getKey(), settingEntry.getValue()); } } } } else if (baseElement.isCopyModel()) { settings.put(CmsContainerElement.MODEL_GROUP_STATE, ModelGroupState.wasModelGroup.name()); } } return CmsContainerElementBean.cloneWithSettings(baseElement, settings); }
java
public Vector2i sub(int x, int y, Vector2i dest) { dest.x = this.x - x; dest.y = this.y - y; return dest; }
python
def clean_html(self, html): """Apply ``Cleaner`` to HTML string or document and return a cleaned string or document.""" result_type = type(html) if isinstance(html, six.string_types): doc = html_fromstring(html) else: doc = copy.deepcopy(html) self(doc) if issubclass(result_type, six.binary_type): return tostring(doc, encoding='utf-8') elif issubclass(result_type, six.text_type): return tostring(doc, encoding='unicode') else: return doc
java
void populateRelationForM2M(Object entity, EntityMetadata entityMetadata, PersistenceDelegator delegator, Relation relation, Object relObject, Map<String, Object> relationsMap) { // For M-M relationship of Collection type, relationship entities are // always fetched from Join Table. if (relation.getPropertyType().isAssignableFrom(List.class) || relation.getPropertyType().isAssignableFrom(Set.class)) { if (relation.isRelatedViaJoinTable() && (relObject == null || ProxyHelper.isProxyOrCollection(relObject))) { populateCollectionFromJoinTable(entity, entityMetadata, delegator, relation); } } else if (relation.getPropertyType().isAssignableFrom(Map.class)) { if (relation.isRelatedViaJoinTable()) { // TODO: Implement Map relationships via Join Table (not // supported as of now) } else { populateCollectionFromMap(entity, delegator, relation, relObject, relationsMap); } } }
java
public final void entry(Class sourceClass, String methodName) { entry(null, sourceClass, methodName, (Object[]) null); }
java
public void reconnect() throws IOException, SlackApiException, URISyntaxException, DeploymentException { // Call rtm.connect again to refresh wss URL RTMConnectResponse response = slack.methods().rtmConnect(RTMConnectRequest.builder().token(botApiToken).build()); if (response.isOk()) { this.wssUri = new URI(response.getUrl()); this.connectedBotUser = response.getSelf(); } else { throw new IllegalStateException("Failed to the RTM endpoint URL (error: " + response.getError() + ")"); } // start a WebSocket session connect(); }
python
def encode(self, reference_boxes, proposals): """ Encode a set of proposals with respect to some reference boxes Arguments: reference_boxes (Tensor): reference boxes proposals (Tensor): boxes to be encoded """ TO_REMOVE = 1 # TODO remove ex_widths = proposals[:, 2] - proposals[:, 0] + TO_REMOVE ex_heights = proposals[:, 3] - proposals[:, 1] + TO_REMOVE ex_ctr_x = proposals[:, 0] + 0.5 * ex_widths ex_ctr_y = proposals[:, 1] + 0.5 * ex_heights gt_widths = reference_boxes[:, 2] - reference_boxes[:, 0] + TO_REMOVE gt_heights = reference_boxes[:, 3] - reference_boxes[:, 1] + TO_REMOVE gt_ctr_x = reference_boxes[:, 0] + 0.5 * gt_widths gt_ctr_y = reference_boxes[:, 1] + 0.5 * gt_heights wx, wy, ww, wh = self.weights targets_dx = wx * (gt_ctr_x - ex_ctr_x) / ex_widths targets_dy = wy * (gt_ctr_y - ex_ctr_y) / ex_heights targets_dw = ww * torch.log(gt_widths / ex_widths) targets_dh = wh * torch.log(gt_heights / ex_heights) targets = torch.stack((targets_dx, targets_dy, targets_dw, targets_dh), dim=1) return targets
java
public static <T extends Enum<T>> T enuum(Class<T> enumClass, String value) { List<Enum> values = (List<Enum>) EnumUtils.valueList(enumClass); for (Enum enumValue : values) { if (enumValue.name().equalsIgnoreCase(value)) { return (T) enumValue; } } return InvalidValues.createInvalidEnum(enumClass, value); }
java
private void readNotationDeclaration() throws IOException, KriptonRuntimeException { read(START_NOTATION); skip(); readName(); if (!readExternalId(false, false)) { throw new KriptonRuntimeException("Expected external ID or public ID for notation", true, this.getLineNumber(), this.getColumnNumber(), getPositionDescription(), null); } skip(); read('>'); }