language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _qnwtrap1(n, a, b): """ Compute univariate trapezoid rule quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) A...
python
def vq_loss(x, targets, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Compute the loss of large vocab tensors using a VQAE codebook. ...
python
def losc_frame_json(ifo, start_time, end_time): """ Get the information about the public data files in a duration of time Parameters ---------- ifo: str The name of the IFO to find the information about. start_time: int The gps time in GPS seconds end_time: int The end t...
java
@Override public void learn(double[] x, int y) { if (model == Model.GENERAL) { throw new UnsupportedOperationException("General-mode Naive Bayes classifier doesn't support online learning."); } if (x.length != p) { throw new IllegalArgumentException("Invalid input ve...
java
@Override public int powerSetSize(int min, int max) { if (min < 1 || max < min) throw new IllegalArgumentException(); final int size = size(); // special cases if (size < min) return 0; if (size == min) return 1; /* * Compute the sum of binomial coefficients ranging from (size ch...
python
def object_permission_set(self): ''' admins, users with team:admin for the team, and users with org:admin, team's organization have full access to teams. Users who are a member of the team, or are a member of the team's organization, have read access to the team. ''' ...
java
public ServiceFuture<Void> logTrackingEventsAsync(String resourceGroupName, String integrationAccountName, TrackingEventsDefinition logTrackingEvents, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(logTrackingEventsWithServiceResponseAsync(resourceGroupName, integrationAccountN...
java
@Override public AssumeRoleResult assumeRole(AssumeRoleRequest request) { request = beforeClientExecution(request); return executeAssumeRole(request); }
java
@Override public SqlContext setupSqlBulkInsertContext(final SqlAgent agent, final SqlContext context, final TableMetadata metadata, final Class<? extends Object> entityType, final int numberOfRecords) { return context.setSql(buildBulkInsertSQL(metadata, entityType, agent.getSqlConfig(), numberOfRecords)); }
java
public static JBBPCompiledBlock compile(final String script, final JBBPCustomFieldTypeProcessor customTypeFieldProcessor) throws IOException { JBBPUtils.assertNotNull(script, "Script must not be null"); final JBBPCompiledBlock.Builder builder = JBBPCompiledBlock.prepare().setSource(script); final List<JBB...
java
@Override public CompletableFuture<VersionedMetadata<EpochTransitionRecord>> submitScale(final List<Long> segmentsToSeal, final List<Map.Entry<Double, Double>> newRanges, ...
java
private void initializePort() throws ChannelException { try { this.endPoint.initServerSocket(); } catch (IOException ioe) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "TCP Channel: " + getExternalName() + "- Problem occurred wh...
java
public final LinkHandler getLink(String linkName) { LinkTypeFilter filter = new LinkTypeFilter(); return (LinkHandler) linkIndex.findByName(linkName, filter); }
python
def _github_store_authorization(cls, user, auth): """Store an authorization token for the given GitHub user in the git global config file. """ ClHelper.run_command("git config --global github.token.{login} {token}".format( login=user.login, token=auth.token), log_secret=Tr...
python
def mark_forums_read(self, forums, user): """ Marks a list of forums as read. """ if not forums or not user.is_authenticated: return forums = sorted(forums, key=lambda f: f.level) # Update all forum tracks to the current date for the considered forums for forum in f...
java
private static <T> int setStatementParameters(final T item, final Introspected introspected, final FieldColumnInfo[] fcInfos, final PreparedStatement stmt, ...
java
public OperationStatusResponseInner startOSUpgrade(String resourceGroupName, String vmScaleSetName) { return startOSUpgradeWithServiceResponseAsync(resourceGroupName, vmScaleSetName).toBlocking().last().body(); }
python
def get_rsc_list_2(self, rsc_clz_list=None): """get the list of resource list to collect based on clz list :param rsc_clz_list: the list of classes to collect :return: filtered list of resource list, like [VNXLunList(), VNXDiskList()] """ rsc_list_2 = self._defa...
java
private void setAdditionalInformation(AdditionalInformation additionalInformation) { Boolean hasInvestigator = false; additionalInformation.addNewFellowshipTrainingAndCareerGoals(); additionalInformation.addNewActivitiesPlannedUnderThisAward(); ProposalPersonContract principalInvesti...
java
@Override protected void initView() { super.initView(); // getRootNode().setPrefSize(1010, 750); // getRootNode().setMinSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE); // getRootNode().setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE); this.slideContent = new StackP...
java
private static RectF getCornerBounds(@NonNull final Orientation orientation, final int size) { switch (orientation) { case TOP_LEFT: return new RectF(0, 0, 2 * size, 2 * size); case TOP_RIGHT: return new RectF(-size, 0, size, 2 * size); case BO...
python
def cog(options): """Run cog against all or a subset of the input source files. Examples:: $ paver cog PyMOTW/atexit $ paver cog PyMOTW/atexit/index.rst $ paver cog See help on paver.doctools.cog for details on the standard options. """ options.order('cog', 'sphinx', add_res...
python
def set_iscsi_info(self, target_name, lun, ip_address, port='3260', auth_method=None, username=None, password=None): """Set iSCSI details of the system in UEFI boot mode. The initiator system is set with the target details like IQN, LUN, IP, Port et...
python
def walk_files_for(paths, supported_extensions): """ Iterating files for given extensions. Args: supported_extensions (list): supported file extentsion for which to check loc and com. Returns: str: yield each full path and filename found. """ for...
java
public HashMap<KafkaTopicPartition, Long> snapshotCurrentState() { // this method assumes that the checkpoint lock is held assert Thread.holdsLock(checkpointLock); HashMap<KafkaTopicPartition, Long> state = new HashMap<>(subscribedPartitionStates.size()); for (KafkaTopicPartitionState<KPH> partition : subscrib...
java
public List<JAXBElement<AbstractRingPropertyType>> getInterior() { if (interior == null) { interior = new ArrayList<JAXBElement<AbstractRingPropertyType>>(); } return this.interior; }
python
def leaf_bus(self, df=False): """ Return leaf bus idx, line idx, and the line foreign key Returns ------- (list, list, list) or DataFrame """ # leafs - leaf bus idx # lines - line idx # fkey - the foreign key of Line, in 'bus1' or 'bus2', linking...
java
public void blockDeployManagedDeploymentsWhenNeeded(@Observes EventContext<DeployManagedDeployments> eventContext) { if (!extensionEnabled()) { eventContext.proceed(); } else if (deployDeployments) { deployDeployments = false; debug("NOT Blocking DeployManaged...
java
@SuppressWarnings("checkstyle:magicnumber") private void writeColumns() throws IOException { for (final DBaseFileField field : this.columns) { // Field name, filled with 0x00 (0-10) writeDBFString(field.getName(), 10, (byte) 0x00); this.stream.writeByte(0x00); // Field type (11) this.stream.writeByt...
python
def receiver(self, value): """Set receiver instance.""" assert isinstance(value, Receiver) self.receiver_id = value.receiver_id
java
protected static ForkJoinTask<?> pollNextLocalTask() { Thread t; return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? ((ForkJoinWorkerThread) t).workQueue.nextLocalTask() : null; }
python
def realign_image(image, shift_x, shift_y, max_shift_x, max_shift_y, shift_angle=0.0, filter=Filter.NearestNeighbor, stretch_factor=None, cropping_box=None): """ Realign the given image providing the specific horizontal and vertical shifts, and crop the image providing the maximum ho...
python
def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): """Look for any references, without object type This always searches in "refspecific" mode """ prefix = node.get('dn:prefix') results = [] match = self.find_obj(env, ...
python
def secrets_manager(*secret_names): """ Get secrets from the `AWS Secrets Manager <https://aws.amazon.com/secrets-manager/>`_. Secrets are added to a dictionary named ``secrets`` on the context object. This requires your lambda to have the ``secretsmanager:GetSecretValue`` permission for the reque...
java
private void visitReturn(NodeTraversal t, Node n) { Node enclosingFunction = t.getEnclosingFunction(); if (enclosingFunction.isGeneratorFunction() && !n.hasChildren()) { // Allow "return;" in a generator function, even if it's not the declared return type. // e.g. Don't warn for a generator function...
python
def updateKronCovs(covs,Acovs,N,P): """ make sure that covs and Acovs are lists """ if (covs is None) and (Acovs is None): covs = [SP.ones([N,1])] Acovs = [SP.eye(P)] if Acovs is None or covs is None: raise Exception("Either Acovs or covs is None, while the other isn't") ...
java
public ServiceFuture<List<JobPreparationAndReleaseTaskExecutionInformation>> listPreparationAndReleaseTaskStatusAsync(final String jobId, final JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions, final ListOperationCallback<JobPreparationAndReleaseTaskExecutionInformation> servi...
python
def infer_enum_class(node): """ Specific inference for enums. """ for basename in node.basenames: # TODO: doesn't handle subclasses yet. This implementation # is a hack to support enums. if basename not in ENUM_BASE_NAMES: continue if node.root().name == "enum": ...
python
def make_structure_from_geos(geos): '''Creates a structure out of a list of geometry objects.''' model_structure=initialize_res(geos[0]) for i in range(1,len(geos)): model_structure=add_residue(model_structure, geos[i]) return model_structure
python
def dict_filter_update(base, updates): # type: (dict, dict) -> None """ Update dict with None values filtered out. """ base.update((k, v) for k, v in updates.items() if v is not None)
java
public int doEndTag() throws JspException { if (hasErrors()) return reportAndExit(EVAL_PAGE); String idScript = null; // Create an appropriate "form" element based on our parameters HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); Serv...
java
public String toUriString(final java.net.URI uri) { return this.toUriString(URI.createURI(uri.normalize().toString())); }
java
@Trivial private static final OnError ignoreWarnOrFail() { String value = null; BundleContext bundleContext = priv.getBundleContext(FrameworkUtil.getBundle(VariableRegistry.class)); ServiceReference<VariableRegistry> ref = priv.getServiceReference(bundleContext, VariableRegistry.class); ...
python
def deprecated(use_instead=None): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" def wrapped(func): @wraps(func) def new_func(*args, **kwargs): message = "Call to deprecated fu...
python
def process_post_media_attachment(self, bulk_mode, api_media_attachment): """ Create or update a Media attached to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_media_attachment: the API data for the Media :return: the Media a...
python
def _climlab_to_cam3(self, field): '''Prepare field with proper dimension order. CAM3 code expects 3D arrays with (KM, JM, 1) and 2D arrays with (JM, 1). climlab grid dimensions are any of: - (KM,) - (JM, KM) - (JM, IM, KM) (longitude dimensi...
python
def to_undirected(self, reciprocal=False): """Return an undirected representation of the dyndigraph. Parameters ---------- reciprocal : bool (optional) If True only keep edges that appear in both directions in the original dyndigraph. Returns -------...
java
public RandomICAutomatonGenerator<SP, TP> withStateProperties(Supplier<? extends SP> spSupplier) { return withStateProperties(r -> spSupplier.get()); }
java
public void async() { final Request request = data.build(); final CallbackHandler handler = request.handler != null ? request.handler : singleton.handler; final boolean safe = request.safe != null ? request.safe : singleton.safe; // Ignore current request if already running (ignoreIfRunning) synchronized (ac...
python
def _unbind(cls, boundname): """ Unbinds a bound form to a WFN. :param string boundname: CPE name :returns: WFN object associated with boundname. :rtype: CPE2_3_WFN """ try: fs = CPE2_3_FS(boundname) except: # CPE name is not form...
java
public void marshall(PendingMaintenanceAction pendingMaintenanceAction, ProtocolMarshaller protocolMarshaller) { if (pendingMaintenanceAction == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(pending...
python
def call(self): """ Make the API call again and fetch fresh data. """ data = self._downloader.download() # Only try to pass errors arg if supported if sys.version >= "2.7": data = data.decode("utf-8", errors="ignore") else: data = data.decode("utf-8") ...
python
def parse_deprecated_tags(self, name, attributes): '''Checks to see if the PDB file has been deprecated and, if so, what the new ID is.''' if name == 'PDBx:pdbx_database_PDB_obs_spr': self.counters['PDBx:pdbx_database_PDB_obs_spr'] = self.counters.get('PDBx:pdbx_database_PDB_obs_spr', 0) + 1...
java
private static String prependSlash(final String path) { if (path.length() == 0 || path.charAt(0) != '/') { /* our path doesn't start with a slash, so we prepend it */ return "/" + path; } return path; }
python
def find_videos_by_ids(self, video_ids): """doc: http://open.youku.com/docs/doc?id=45 """ url = 'https://openapi.youku.com/v2/videos/show_basic_batch.json' params = { 'client_id': self.client_id, 'video_ids': video_ids } r = requests.get(url, param...
python
def _writeMapTable(self, session, fileObject, mapTable, replaceParamFile): """ Write Generic Map Table Method This method writes a mapping table in the generic format to file. The method will handle both empty and filled cases of generic formatted mapping tables. session = SQLA...
java
@Override public Query setParameter(int position, Object value) { kunderaQuery.setParameter(position, value); return this; }
python
def _check_covariance(covariance): """ Check and modify the covariance matrix in the case of "infinitely" thin detections. This follows SExtractor's prescription of incrementally increasing the diagonal elements by 1/12. """ p = 1. / 12 # arbitrary SExtracto...
java
@Help( help = "Create the PhysicalNetworkFunctionDescriptor of a NetworkServiceDescriptor with specific id" ) public PhysicalNetworkFunctionDescriptor createPhysicalNetworkFunctionDescriptor( final String idNsd, final PhysicalNetworkFunctionDescriptor physicalNetworkFunctionDescriptor) throw...
python
def clear(self): """Clear output from one (derived) class loader """ # mark this task as incomplete self.mark_incomplete() # Delete the indicator metadata, this also deletes values by cascading. # # NOTE: calling 'delete()' on the query (instead of on the queried...
java
protected Content getNavSummaryLink(ClassDoc cd, boolean link) { if (link) { if (cd == null) { return writer.getHyperLink( SectionName.FIELD_SUMMARY, writer.getResource("doclet.navField")); } else { return wr...
python
def hicpro_mapping_chart (self): """ Generate the HiC-Pro Aligned reads plot """ # Specify the order of the different possible categories keys = OrderedDict() keys['Full_Alignments_Read'] = { 'color': '#005ce6', 'name': 'Full reads Alignments' } keys['Trimmed_Alignments_Read']...
java
@SuppressWarnings("unchecked") public <T> TypeAdapter<T> getAdapter(TypeToken<T> type) { TypeAdapter<?> cached = typeTokenCache.get(type == null ? NULL_KEY_SURROGATE : type); if (cached != null) { return (TypeAdapter<T>) cached; } Map<TypeToken<?>, FutureTypeAdapter<?>> threadCalls = calls.get(...
java
private NodeInclude[] getNodeIncludes(Node config) throws IllegalNameException, RepositoryException { List<NodeInclude> includes = new ArrayList<NodeInclude>(); NodeList childNodes = config.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node n = childNodes.item(i...
java
public static long getDelayMillis(String time) { String pattern = "HH:mm"; Date now = new Date(); if (StringUtils.contains(time, "-")) { String start = time.split("-")[0]; String end = time.split("-")[1]; if (StringUtils.contains(start, ":") && StringUtils.contains(end, ":")) { Date d1 = getCurrentDa...
java
private void handleElementCollectionAttribute(CQLTranslator translator, Attribute attribute, StringBuilder typeQueryBuilder) { String dataType = CassandraValidationClassMapper.getValidationClass(attribute.getJavaType(), true); // CQL Type of collection column String collectionCq...
python
def format_timestamp( ts: Union[int, float, tuple, time.struct_time, datetime.datetime] ) -> str: """Formats a timestamp in the format used by HTTP. The argument may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.gmtime`, or a `datetime.datetime` object. >...
python
def generate(self): """ Generate sample settings """ otype = getattr(self, 'GENERATE') if otype: if otype == 'env': self.generate_env() elif otype == "command": self.generate_command() elif otype == "docker-run": ...
python
def edges_to_path(edges, vertices, **kwargs): """ Given an edge list of indices and associated vertices representing lines, generate kwargs for a Path object. Parameters ----------- edges : (n, 2) int Vertex indices of line segments vertices : (m, d...
python
def compile_sass(self, sass_filename, sass_fileurl): """ Compile the given SASS file into CSS """ compile_kwargs = { 'filename': sass_filename, 'include_paths': SassProcessor.include_paths + APPS_INCLUDE_DIRS, 'custom_functions': get_custom_functions()...
python
def filter_transition_coefs(transition_coef, indices): """ >>> coef = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> filter_transition_coefs(coef, [0]) array([[0]]) >>> filter_transition_coefs(coef, [1, 2]) array([[4, 5], [7, 8]]) >>> filter_transition_coefs(coef, [2, 0]) arr...
java
private static int parseIntKey(CharSequence key) { int numSpaces = 0; StringBuilder digits = new StringBuilder(); // build a string from the numerical characters for (int i=0; i<key.length(); i++) { char c = key.charAt(i); if (' ' == c) { numSpace...
python
def link_text(self): """ Get a text represention of the links node. :return: """ s = '' links_node = self.metadata.find('links') if links_node is None: return s links = links_node.getchildren() if links is None: return s ...
java
public static AnnotationAttributes getAnnotationAttributes(Annotation annotation, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { AnnotationAttributes attrs = new AnnotationAttributes(); Method[] methods = annotation.annotationType().g...
python
def clone(self, parent=None): """ Deep clone of this element and children. @param parent: An optional parent for the copied fragment. @type parent: I{Element} @return: A deep copy parented by I{parent} @rtype: I{Element} """ root = Element(self.qname(), ...
python
def extract_specific_interval(self, interval_start, interval_end): """ Overload if special behaviour is required when a series ends. """ interval_start = int(interval_start) interval_end = int(interval_end) if interval_start >= interval_end: raise ValueError...
java
@Override protected void setInterestedInWrite(NioSessionEx session, boolean isInterested) throws Exception { SelectionKey key = session.getSelectionKey(); int oldInterestOps = key.interestOps(); int newInterestOps = oldInterestOps; if (isInterested) { newInterestOps |= S...
python
def strakos(n, l_min=0.1, l_max=100, rho=0.9): """Return the Strakoš matrix. See [Str92]_. """ d = [l_min + (i-1)*1./(n-1)*(l_max-l_min)*(rho**(n-i)) for i in range(1, n+1)] return numpy.diag(d)
java
void deleteEdgesBreakFaces_(AttributeStreamOfInt32 edgesToDelete) { for (int i = 0, n = edgesToDelete.size(); i < n; i++) { int half_edge = edgesToDelete.get(i); int chain = getHalfEdgeChain(half_edge); int halfEdgeTwin = getHalfEdgeTwin(half_edge); int chainTwin = getHalfEdgeChain(halfEdgeTwin); setCh...
java
public void setRobotApplicationNames(java.util.Collection<String> robotApplicationNames) { if (robotApplicationNames == null) { this.robotApplicationNames = null; return; } this.robotApplicationNames = new java.util.ArrayList<String>(robotApplicationNames); }
python
def on_processing_error(self): """Called when message processing failure happens due to a ConsumerException or an unhandled exception. """ duration = time.time() - self.last_failure if duration > self.MAX_ERROR_WINDOW: LOGGER.info('Resetting failure window, %i second...
python
def binary_classification_metrics(y_true, y_pred, y_prob): #TODO: update description """classification_metrics. This function cal... Parameters ---------- y_true : array-like Ground truth (correct) labels. y_pred : array-like Predicted labels, as returned by a classifier. ...
java
@Override public QueryAggregation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonReader in = new JsonReader(new StringReader(GsonSingleton.getGson().toJson(json))); HashMap<String, Object> aggregationMap = null; try { aggregatio...
java
public Long reserveAdd(String transactionId, Data value) { if (value != null && getCollection().contains(new CollectionItem(INVALID_ITEM_ID, value))) { return null; } final long itemId = nextId(); txMap.put(itemId, new TxCollectionItem(itemId, null, transactionId, false)); ...
python
def slicelist(b): """Produce a list of slices given the boolean array b. Start and stop in each slice describe the True sections in b.""" slicelst = [] started = False for i, e in enumerate(b): if e and not started: start = i started = True elif not e and st...
java
public String replaceFieldTypes(String pattern, String skeleton) { return replaceFieldTypes(pattern, skeleton, MATCH_NO_OPTIONS); }
java
static void unregister(final Object value) { Set<IDKey> registry = getRegistry(); if (registry != null) { registry.remove(new IDKey(value)); synchronized (HashCodeBuilder.class) { //read again registry = getRegistry(); if (registry ...
java
public void process() throws CmdLineException { ProcessingContext context = new ProcessingContext(); for (String arg : this.args) { if (arg != null && !context.processPendingOptionAction(arg) && !context.processOptionAction(arg, this.optionActions) && !context.processSwitchAction(arg, this.switchActio...
python
def get_instance(self, payload): """ Build an instance of DependentPhoneNumberInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.address.dependent_phone_number.DependentPhoneNumberInstance :rtype: twilio.rest.api.v2010.account.ad...
python
def get_swagger_view(title=None, url=None, patterns=None, urlconf=None): """ Returns schema view which renders Swagger/OpenAPI. """ class SwaggerSchemaView(APIView): _ignore_model_permissions = True exclude_from_schema = True permission_classes = [AllowAny] renderer_class...
python
def setApparentDecel(self, typeID, decel): """setDecel(string, double) -> None Sets the apparent deceleration in m/s^2 of vehicles of this type. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_APPARENT_DECEL, typeID, decel)
java
public TVSeasonInfo getSeasonInfo(int tvID, int seasonNumber, String language, String... appendToResponse) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); parameters.add(Param.SEASON_NUMBER, seasonNumber); parameters.add(Param.L...
java
public static short[] asShortTypeArray(List<Short> input) { short[] result = new short[input.size()]; for (int i = 0; i < result.length; i++) { result[i] = input.get(i); } return result; }
python
def on_draw(): global yrot win.clear() glLoadIdentity() glTranslatef(0, 0, -100) glRotatef(yrot, 0.0, 1.0, 0.0) default_system.draw() ''' glBindTexture(GL_TEXTURE_2D, 1) glEnable(GL_TEXTURE_2D) glEnable(GL_POINT_SPRITE) glPointSize(100); glBegin(GL_POINTS) glVertex2f(0,0) glEnd() glBindTexture(GL_TEXTURE...
java
public String getControlProperty(String strKey, String strDefaultValue) { String strValue = ((PropertiesField)this.getRecord(MessageControl.MESSAGE_CONTROL_FILE).getField(MessageControl.PROPERTIES)).getProperty(strKey); if (strValue == null) { if (strDefaultValue == null) ...
python
def _get_cascading_attr(self, attr_name, *args): """ Will traverse the configuration data looking for attr_name provided. It will know where to look for the attribute based on the *args that are passed to the method. It treats the args as ancestors starting with the oldest `root -> grandparent...
python
def dependencies_as_list(self): """Returns a list of dependency names.""" dependencies = [] for dependency in self.dependencies: dependencies.append(dependency.name) return dependencies
java
public static void copyPropertiesToMap(Object bean, String prefix, Map<String, Object> map) { Class clazz = bean.getClass(); Method[] methods = bean.getClass().getMethods(); for (Method method : methods) { // 复制属性 Class returnc = method.getReturnType(); if (Re...
python
def convert_coord(coord_from,matrix_file,base_to_aligned=True): '''Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False...
java
public static UpdateMonitor getMonitor(File monitoredFile, MonitorType type, String filter) { if (monitoredFile == null) throw new NullPointerException("MonitoredFile must be non-null"); if (type == null) throw new NullPointerException("MonitorType must be non-null"); s...