language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def squad(R_in, t_in, t_out): """Spherical "quadrangular" interpolation of rotors with a cubic spline This is the best way to interpolate rotations. It uses the analog of a cubic spline, except that the interpolant is confined to the rotor manifold in a natural way. Alternative methods involving ...
java
private void processResources() throws SQLException { List<Row> permanentRows = getTable("PERMANENT_RESOURCE"); List<Row> consumableRows = getTable("CONSUMABLE_RESOURCE"); Collections.sort(permanentRows, PERMANENT_RESOURCE_COMPARATOR); Collections.sort(consumableRows, CONSUMABLE_RESOURCE_COM...
java
public static RgbaColor from(String color) { if (color.startsWith("#")) { return fromHex(color); } else if (color.startsWith("rgba")) { return fromRgba(color); } else if (color.startsWith("rgb")) { return fromRgb(color); } else ...
java
@Override protected void _fit(Dataframe trainingData) { ModelParameters modelParameters = knowledgeBase.getModelParameters(); TrainingParameters trainingParameters = knowledgeBase.getTrainingParameters(); Map<Object, Double> weights = modelParameters.getWeights(); Ma...
python
def js_query(self, query: str) -> Awaitable: """Send query to related DOM on browser. :param str query: single string which indicates query type. """ if self.connected: self.js_exec(query, self.__reqid) fut = Future() # type: Future[str] self.__tasks...
java
public alluxio.grpc.SaslMessageType getMessageType() { alluxio.grpc.SaslMessageType result = alluxio.grpc.SaslMessageType.valueOf(messageType_); return result == null ? alluxio.grpc.SaslMessageType.CHALLENGE : result; }
python
def noaa_prompt(): """ Convert between NOAA and LiPD file formats. :return: """ logger_noaa.info("enter noaa") # Run lpd_noaa or noaa_lpd ? print("Which conversion?\n1. LPD to NOAA\n2. NOAA to LPD\n") mode = input("Option: ") logger_noaa.info("chose option: {}".format(mode)) ret...
python
def create_conversation(self, recipients, body, **kwargs): """ Create a new Conversation. :calls: `POST /api/v1/conversations \ <https://canvas.instructure.com/doc/api/conversations.html#method.conversations.create>`_ :param recipients: An array of recipient ids. Th...
java
public static boolean isLeapYear(int y) { boolean result = false; if (((y % 4) == 0) && // must be divisible by 4... ((y < 1582) || // and either before reform year... ((y % 100) != 0) || // or not a century... ((y % 400) == 0))) { // or a multiple of 400... result = true; // for leap year. } ...
java
public void set(T newValue) { Preconditions.checkNotNull(newValue, "Monitored value can not be null"); if (Objects.equal(this.value, newValue)) { return; } this.value = newValue; notifyMonitors(); }
python
def _partial(self): """Callback for partial output.""" raw_stdout = self._process.readAllStandardOutput() stdout = handle_qbytearray(raw_stdout, self._get_encoding()) if self._partial_stdout is None: self._partial_stdout = stdout else: self._partial_stdou...
python
def build(self, root, schema): """ Build the syntax tree for kubectl command line """ if schema.get("subcommands") and schema["subcommands"]: for subcmd, childSchema in schema["subcommands"].items(): child = CommandTree(node=subcmd) child = self.build(child, c...
python
def _verify(self): """Some sanity checks on GPG.""" if not self.keyid: raise ValueError('No GPG key specified for signing, did you mean to use --no-sign?') sign = self.gpg.sign('', keyid=self.keyid) if 'secret key not available' in sign.stderr: raise ValueError('K...
java
public static long deepMemoryUsageOf(Instrumentation inst, final Object obj, final int referenceFilter) { return deepMemoryUsageOf0(inst, new HashSet<Integer>(), obj, referenceFilter); }
java
public static RangeImpl range( EvaluationContext ctx, Range.RangeBoundary lowBoundary, Object lowEndPoint, Object highEndPoint, Range.RangeBoundary highBoundary) { Comparable left = asComparable(lowEndPoint); Comparable right = asComparable(hi...
python
def OnPasteFormat(self, event): """Paste format event handler""" with undo.group(_("Paste format")): self.grid.actions.paste_format() self.grid.ForceRefresh() self.grid.update_attribute_toolbar() self.grid.actions.zoom()
java
public static boolean hasMixin(final Node node) { try { return node.isNodeType(FEDORA_WEBAC_ACL); } catch (final RepositoryException e) { throw new RepositoryRuntimeException(e); } }
python
def MASTRADec(ra, dec, darcsec, stars_only=False): ''' Detector location retrieval based upon RA and Dec. Adapted from `PyKE <http://keplergo.arc.nasa.gov/PyKE.shtml>`_. ''' # coordinate limits darcsec /= 3600.0 ra1 = ra - darcsec / np.cos(dec * np.pi / 180) ra2 = ra + darcsec / np.cos...
python
def _easteregg(app=None): """Like the name says. But who knows how it works?""" def bzzzzzzz(gyver): import base64 import zlib return zlib.decompress(base64.b64decode(gyver)).decode("ascii") gyver = u"\n".join( [ x + (77 - len(x)) * u" " for x in b...
python
def start(self): """ Starts the scheduler in a new thread. Returns 0 if success. In standalone mode, this method will block until there are no more scheduled jobs. """ self.history.append("Started on %s" % time.asctime()) self.start_time = time.time() if not has_...
java
private void _serialize(Object object, StringBuilder sb, Set<Object> done) throws ConverterException { // try { deep++; // NULL if (object == null) { sb.append(goIn()); sb.append("nullValue()"); deep--; return; } // String if (object instanceof String) { sb.append(goIn()); sb.append...
java
public JobScheduleInner get(String resourceGroupName, String automationAccountName, UUID jobScheduleId) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName, jobScheduleId).toBlocking().single().body(); }
python
def p_scalar_group(self, p): """ scalar_group : SCALAR | scalar_group SCALAR """ if len(p) == 2: p[0] = (str(p[1]),) if len(p) == 3: p[0] = p[1] + (str(p[2]),) if len(p) == 4: p[0] = p[1] + (str(p[3]),)
java
public V getValue(long timeout, Callable<V> updater, boolean returnExpiredWhileUpdating, Object cacheRequestObject) { if (!isInitialized() || hasExpired(timeout, cacheRequestObject)) { boolean lockAcquired = false; try { long beforeLockingCreatedMillis = createdMillis; ...
java
@Override public void executeQuery(boolean mustExecuteOnMaster, Results results, final String sql) throws SQLException { cmdPrologue(); try { writer.startPacket(0); writer.write(COM_QUERY); writer.write(sql); writer.flush(); getResult(results); } catch (SQLException ...
python
def prebuild_arch(self, arch): '''Run any pre-build tasks for the Recipe. By default, this checks if any prebuild_archname methods exist for the archname of the current architecture, and runs them if so.''' prebuild = "prebuild_{}".format(arch.arch.replace('-', '_')) if hasattr(s...
python
def create_precursor_quant_lookup(quantdb, mzmlfn_feats, quanttype, rttol, mztol, mztoltype): """Fills quant sqlite with precursor quant from: features - generator of xml features from openms """ featparsermap = {'kronik': kronik_featparser, 'op...
java
@Override public void unRegisterEvents(String handlerName) { if (handlerEventsMap.containsKey(handlerName)) { if (handlerEventsMap.size() == 1) { auditStopped(null); } handlerEventsMap.remove(handlerName); } if (tc.isDebugEnabled()) { ...
java
public static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags) throws NativeIOException { if (nativeLoaded && fadvisePossible) { try { posix_fadvise(fd, offset, len, flags); InjectionHandler.processEvent( InjectionEventCore.NATIVEIO_POSI...
python
def get_default_value(self): """ return default value """ default = self.default_value if isinstance(default, collections.Callable): default = default() return default
python
def oid2name(self, oid): "Look up the parameter name for a given OID" if not self._oid_lookup: for name, data in self._parameters.items(): self._oid_lookup[data['OID']] = data['Name'] return self._oid_lookup[oid]
java
public Observable<ServiceResponse<Page<StorageAccountItem>>> getStorageAccountsWithServiceResponseAsync(final String vaultBaseUrl, final Integer maxresults) { return getStorageAccountsSinglePageAsync(vaultBaseUrl, maxresults) .concatMap(new Func1<ServiceResponse<Page<StorageAccountItem>>, Observable...
java
@Override public void setAttributes(final Map<String, List<Object>> attrs) { for (final Entry<String, List<Object>> attrEntry : attrs.entrySet()) { final String key = attrEntry.getKey(); final List<Object> value = attrEntry.getValue(); setAttribute(key, value); } ...
java
protected void getOracleTablespaces(Map<String, String> dbPoolData) { String dataTablespace = "users"; String indexTablespace = "users"; CmsSetupDb setupDb = new CmsSetupDb(null); try { setupDb.setConnection( dbPoolData.get("driver"), dbPoolD...
python
def _set_splits(self, split_dict): """Split setter (private method).""" # Update the dictionary representation. # Use from/to proto for a clean copy self._splits = split_dict.copy() # Update the proto del self.as_proto.splits[:] # Clear previous for split_info in split_dict.to_proto(): ...
java
static void releaseContext(SeaGlassContext context) { synchronized (contextMap) { List instances = (List) contextMap.get(context.getClass()); if (instances == null) { instances = new ArrayList(5); contextMap.put(context.getClass(), instances); ...
python
def right(ctx, text, num_chars): """ Returns the last characters in a text string """ num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") elif num_chars == 0: return '' else: return conversions.to_...
python
def resultManager(self, text): """ resultcode & message: 0 = success => if "resultvalue" = null: no result to show 11 = Not Exist Path 36 = File Infomation Not Found 2002 = Invalidation Cookie """ j = json.loads(text) if j...
java
public void setDistanceFormatter(DistanceFormatter distanceFormatter) { if (distanceFormatter != null && !distanceFormatter.equals(this.distanceFormatter)) { this.distanceFormatter = distanceFormatter; } }
java
private Runnable createStopTask() { return new Runnable() { @Override public void run() { try { // Close the ZK connection in this task will make sure if there is ZK connection created // after doStop() was called but before this task has been executed is also closed. ...
python
def is_printable(c): '''see if a character is printable''' global have_ascii if have_ascii: return ascii.isprint(c) if isinstance(c, int): ic = c else: ic = ord(c) return ic >= 32 and ic <= 126
java
@Override public IDocumentQuery<T> orderByDistanceDescending(DynamicSpatialField field, String shapeWkt) { _orderByDistanceDescending(field, shapeWkt); return this; }
java
@Override public IPortalUrlBuilder getPortalUrlBuilderByLayoutNode( HttpServletRequest request, String layoutNodeId, UrlType urlType) { final IPortletWindowId portletWindowId = getPortletWindowId(request, layoutNodeId); return new PortalUrlBuilder( this.urlSyntaxProvider...
java
@Override public CollectionAttribute<X, ?> getDeclaredCollection(String paramName) { PluralAttribute<X, ?, ?> declaredAttrib = getDeclaredPluralAttribute(paramName); if (isCollectionAttribute(declaredAttrib)) { return (CollectionAttribute<X, ?>) declaredAttrib; } ...
python
def render(self, **kwargs): """ Plots the 2D curve and the control points polygon. """ # Calling parent function super(VisCurve2D, self).render(**kwargs) # Initialize variables legend_proxy = [] legend_names = [] # Draw control points polygon and the curve ...
python
def req_withdraw(self, address, amount, currency, fee=0, addr_tag="", _async=False): """ 申请提现虚拟币 :param address: :param amount: :param currency:btc, ltc, bcc, eth, etc ...(火币Pro支持的币种) :param fee: :param addr_tag: :return: { "status": "ok"...
python
def get_token(filename=TOKEN_PATH, envvar=TOKEN_ENVVAR): """ Returns pipeline_token for API Tries local file first, then env variable """ if os.path.isfile(filename): with open(filename) as token_file: token = token_file.readline().strip() else: token = os.environ.g...
java
public SingletonStoreConfigurationBuilder<S> pushStateTimeout(long l, TimeUnit unit) { return pushStateTimeout(unit.toMillis(l)); }
python
def select_idle_worker(action, action_space, select_worker): """Select an idle worker.""" del action_space action.action_ui.select_idle_worker.type = select_worker
java
public ObjectName createCustomComponentMBeanName(final String type, final String name) { ObjectName result = null; String tmp = jmxDomainName + ":" + "type=" + sanitizeString(type) + ",name=" + sanitizeString(name); try { result = new ObjectName(tmp); } catch (Mal...
java
@Override public Service resolveServiceFrom(final Service service) { val result = getEntityIdAsParameter(service); if (result.isPresent()) { val entityId = result.get(); LOGGER.debug("Located entity id [{}] from service authentication request at [{}]", entityId, service.getId...
python
def get_option_names(self): """returns a list of fully qualified option names. returns: a list of strings representing the Options in the source Namespace list. Each item will be fully qualified with dot delimited Namespace names. """ return [x for x...
python
def correct_rates(rates, opt_qes, combs): """Applies optimal qes to rates. Should be closer to fitted_rates afterwards. Parameters ---------- rates: numpy array of rates of all PMT combinations opt_qes: numpy array of optimal qe values for all PMTs combs: pmt combinations used to correct ...
java
private static String calculateMessageBodyMd5(String messageBody) { if (log.isDebugEnabled()) { log.debug("Message body: " + messageBody); } byte[] expectedMd5; try { expectedMd5 = Md5Utils.computeMD5Hash(messageBody.getBytes(UTF8)); } catch (Exception e) ...
java
public void marshall(GetSnowballUsageRequest getSnowballUsageRequest, ProtocolMarshaller protocolMarshaller) { if (getSnowballUsageRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { } catch (Exception e) { throw ...
java
public Nfs3ReaddirplusResponse wrapped_getReaddirplus(NfsReaddirplusRequest request, final List<NfsDirectoryPlusEntry> entries) throws IOException { NfsResponseHandler<Nfs3ReaddirplusResponse> responseHandler = new NfsResponseHandler<Nfs3ReaddirplusResponse>() { /* (non-Javadoc) ...
python
def to_unit(value, unit='B'): """Convert bytes to give unit.""" byte_array = ['B', 'KB', 'MB', 'GB', 'TB'] if not isinstance(value, (int, float)): value = float(value) if unit in byte_array: result = value / 1024**byte_array.index(unit) return round(result, PRECISION), unit ...
python
def fetch(self, failures=True, wait=0): """ get the task result objects from the chain when it finishes. blocks until timeout. :param failures: include failed tasks :param int wait: how many milliseconds to wait for a result :return: an unsorted list of task objects """ ...
python
def pymmh3_hash128_x64(key: Union[bytes, bytearray], seed: int) -> int: """ Implements 128-bit murmur3 hash for x64, as per ``pymmh3``, with some bugfixes. Args: key: data to hash seed: seed Returns: integer hash """ def fmix(k): k ^= k >> 33 k = (k...
java
public void setSamplingRuleRecords(java.util.Collection<SamplingRuleRecord> samplingRuleRecords) { if (samplingRuleRecords == null) { this.samplingRuleRecords = null; return; } this.samplingRuleRecords = new java.util.ArrayList<SamplingRuleRecord>(samplingRuleRecords); ...
python
def _getFilename(self, fileNumber): """ Given a file number, get its name (if any). @param fileNumber: An C{int} file number. @return: A C{str} file name or C{None} if a file with that number has not been added. """ cur = self._connection.cursor() cur...
java
public static HttpResponse execute(final String url, final String method, final String basicAuthUsername, final String basicAuthPassword, final Map<String, Object> ...
python
def run_remove_system(name, token, org, system, prompt): """ Removes a system from the repo. """ repo = get_repo(token=token, org=org, name=name) try: label = repo.get_label(name=system.strip()) label.delete() click.secho("Successfully deleted {}".format(system), fg="green") ...
java
protected Locator byHeader(int colIndex) { if (colIndex < 1) { throw new IllegalArgumentException("Column index must be greater than 0."); } String xpath = headerTag.isPresent() ? "./thead/tr[1]/th[" + colIndex + "]" : "./tr[1]/th[" + colIndex + "]"; ...
python
def find(entity, **kwargs): """Return all TypedFields found on the input `Entity` that were initialized with the input **kwargs. Example: >>> find(myentity, multiple=True, type_=Foo) Note: TypedFields.__init__() can accept a string or a class as a type_ argument, but this metho...
python
def incoming_connections(self): """Returns a list of all incoming connections for this peer.""" # Incoming connections are on the left. return list( takewhile(lambda c: c.direction == INCOMING, self.connections) )
java
@Override public int deleteById(TableColumnKey id) throws SQLException { int count = 0; if (id != null) { DataColumns dataColumns = queryForId(id); if (dataColumns != null) { count = delete(dataColumns); } } return count; }
python
def label_search(self, label:str) -> List[dict]: ''' Returns the rows in InterLex associated with that label Note: Pressumed to have duplicated labels in InterLex Args: label: label of the entity you want to find Returns: None or List[dict] ''...
python
def k_fold_cross_validation( fitters, df, duration_col, event_col=None, k=5, evaluation_measure=concordance_index, predictor="predict_expectation", predictor_kwargs={}, fitter_kwargs={}, ): # pylint: disable=dangerous-default-value,too-many-arguments,too-many-locals """ Perf...
python
def applicable_file_flags(self): """ Return the applicable file flags attribute of the BFD file being processed. """ if not self._ptr: raise BfdException("BFD not initialized") return _bfd.get_bfd_attribute( self._ptr, BfdAttributes.APPLICABLE_FI...
python
def aggregate_repo(repo, args, sem, err_queue): """Aggregate one repo according to the args. Args: repo (Repo): The repository to aggregate. args (argparse.Namespace): CLI arguments. """ try: logger.debug('%s' % repo) dirmatch = args.dirmatch if not match_dir(r...
java
static RedisFuture<String> alwaysOkOfAsync(Map<?, ? extends CompletionStage<String>> executions) { return new PipelinedRedisFuture<>(executions, objectPipelinedRedisFuture -> { synchronize(executions); return "OK"; }); }
java
public void setPropertyDefaults(String enabled, String showNavigation) { setPropertiesEnabled(Boolean.valueOf(enabled).booleanValue()); setShowNavigation(Boolean.valueOf(showNavigation).booleanValue()); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LO...
java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { if (sessionSynchronization) { String syncKey = getSyncKey(request); synchronized (getSyncObject(syncKey)) { try { doService(request, response); ...
java
public EList<LLERG> getRG() { if (rg == null) { rg = new EObjectContainmentEList.Resolving<LLERG>(LLERG.class, this, AfplibPackage.LLE__RG); } return rg; }
java
@Override public <T> ICompletableFuture<ReadResultSet<T>> readFromEventJournal( long startSequence, int minSize, int maxSize, int partitionId, java.util.function.Predicate<? super EventJournalMapEvent<K, V>> predicate, java.util.function.Functi...
python
def _get_normal_peptides(job, mhc_df, iars, peplen): """ Get the corresponding normal peptides for the tumor peptides that have already been subjected to mhc:peptide binding prediction. :param pandas.DataFrame mhc_df: The dataframe of mhc:peptide binding results :param dict iars: The dict of lists ...
java
public static <K, V> ConvertingComparator<Map.Entry<K, V>, V> mapEntryValues( Comparator<V> comparator) { return new ConvertingComparator<Map.Entry<K,V>, V>(comparator, new Converter<Map.Entry<K, V>, V>() { public V convert(Map.Entry<K, V> source) { return source.getValue(); } }); }
java
private void fixN0c(BracketData bd, int openingIndex, int newPropPosition, byte newProp) { /* This function calls itself recursively */ IsoRun pLastIsoRun = bd.isoRuns[bd.isoRunLast]; Opening qOpening; int k, openingPosition, closingPosition; for (k = openingIndex+1; k < pLastIso...
java
public boolean isPublisherWrapped(AbstractProject<?, ?> project, Class<T> type) { return find(project, type) != null; }
java
public int readRawLittleEndian32() throws IOException { // final byte[] buffer = this.buffer; // int offset = this.offset; final byte[] bs = new byte[4]; buffer.get(bs); // final byte b1 = buffer[offset++]; // final byte b2 = buffer[offset++]; // final byte ...
java
public static GrayU16 convert(GrayF32 input, GrayU16 output) { if (output == null) { output = new GrayU16(input.width, input.height); } else { output.reshape(input.width,input.height); } // threaded code is not significantly faster here ImplConvertImage.convert(input, output); return output; }
java
public com.squareup.okhttp.Call getUniverseConstellationsConstellationIdAsync(Integer constellationId, String acceptLanguage, String datasource, String ifNoneMatch, String language, final ApiCallback<ConstellationResponse> callback) throws ApiException { com.squareup.okhttp.Call call = ...
python
def add_permissions(self, user_id, permissions): """Enables a list of permissions for a user :param int id: user id to set :param list permissions: List of permissions keynames to enable :returns: True on success, Exception otherwise Example:: add_permissions(123, [...
java
public final void mINSERT() throws RecognitionException { try { int _type = INSERT; int _channel = DEFAULT_TOKEN_CHANNEL; // druidG.g:581:11: ( ( 'INSERT' | 'insert' ) ) // druidG.g:581:12: ( 'INSERT' | 'insert' ) { // druidG.g:581:12: ( 'INSERT' | 'insert' ) int alt1=2; int LA1_0 = input.LA(1...
java
private CacheLoaderArgument initializeCacheLoaderArgument(final boolean filterTemplateCatalog) { final LoaderCallback loaderCallback = new LoaderCallback() { @Override public Catalog loadCatalog(final List<String> catalogXMLs, final Long tenantRecordId) throws CatalogApiException { ...
java
public String toTimeStr() { if (null != this.timeZone) { final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DatePattern.NORM_TIME_PATTERN); simpleDateFormat.setTimeZone(this.timeZone); return toString(simpleDateFormat); } return toString(DatePattern.NORM_TIME_FORMAT); }
java
public VpnConnectionInner createOrUpdate(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters).toBlocking().last().body(); }
python
def create_segs_from_cats_job(cp, out_dir, ifo_string, tags=None): """ This function creates the CondorDAGJob that will be used to run ligolw_segments_from_cats as part of the workflow Parameters ----------- cp : pycbc.workflow.configuration.WorkflowConfigParser The in-memory representa...
python
def error_message(): """ Writes out error message specifying the valid commands. Returns: Failure code for system exit """ sys.stderr.write('valid commands:\n') for cmd in get_valid_commands(): sys.stderr.write('\t%s\n' % cmd) return -1
java
@Override public ExportBackupPlanTemplateResult exportBackupPlanTemplate(ExportBackupPlanTemplateRequest request) { request = beforeClientExecution(request); return executeExportBackupPlanTemplate(request); }
java
@Override public int updateId(GeometryIndex data, GeometryIndexKey newId) throws SQLException { int count = 0; GeometryIndex readData = queryForId(data.getId()); if (readData != null && newId != null) { readData.setId(newId); count = update(readData); } return count; }
java
public void attach(Object self) throws IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { for (Class<?> currentClass = self.getClass(); currentClass != Object.class;) { if (Proxy.class.isAssignableFrom(currentClass)) { currentClass = currentClass.getSupercla...
java
private void undeployModule(final InstanceContext instance, final CountingCompletionHandler<Void> counter) { deploymentIDs.remove(instance.address(), new Handler<AsyncResult<String>>() { @Override public void handle(AsyncResult<String> result) { if (result.failed()) { counter.fail(resu...
java
protected Set<String> getPermittedOwnAttributes( final IAuthorizationPrincipal principal, final Set<String> generallyPermittedAttributes) { // The permttedOwnAttributes collection includes all the generallyPermittedAttributes final Set<String> rslt = new HashSet<>(generallyPermi...
python
def http_get(self, request_url): """ This function recieves the request url and it is used internally to get the information via http. Returns the response content. Raises Timeout, TooManyRedirects, RequestException. Raises KeyError if headers are not present. Rai...
python
def set_property(self, name, value): """ Helper to set a property value by name, translating to correct dbus type See also :py:meth:`get_property` :param str name: The property name in the object's dictionary whose value shall be set. :param value: Propertie...
java
public void putCachedAttributesFor(final RegisteredService registeredService, final CachingPrincipalAttributesRepository repository, final String id, final Map<String, List<Object>> attributes) { val cache = getRegisteredServiceCacheI...
python
def readTableFromCSV(f, dialect="excel"): """ Reads a table object from given CSV file. """ rowNames = [] columnNames = [] matrix = [] first = True for row in csv.reader(f, dialect): if first: columnNames = row[1:] first = False else: ...
java
public String createRuleMenu(RuleMenu menu) { String url = WxEndpoint.get("url.menu.create.condition"); if(menu.getRule() == null) { throw new IllegalArgumentException("个性化菜单rule不能为空"); } String json = JsonMapper.nonEmptyMapper().toJson(menu); logger.debug("crea...