language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _databunch_load_empty(cls, path, fname:str='export.pkl'): "Load an empty `DataBunch` from the exported file in `path/fname` with optional `tfms`." sd = LabelLists.load_empty(path, fn=fname) return sd.databunch()
python
def generate_checksums(directory, blacklist=_BLACKLIST): """ Compute checksum for each file in `directory`, with exception of files specified in `blacklist`. Args: directory (str): Absolute or relative path to the directory. blacklist (list/set/tuple): List of blacklisted filenames. Onl...
python
def normalizeGlyphNote(value): """ Normalizes Glyph Note. * **value** must be a :ref:`type-string`. * Returned value is an unencoded ``unicode`` string """ if not isinstance(value, basestring): raise TypeError("Note must be a string, not %s." % type(value).__name...
java
public void addMultipleItems(int times, final Object... values) { for (int i = 0; i < times; i++) { addItemAsArray(values); } }
java
public Object parseIdRefElement(Element ele) { // A generic reference to any name of any bean. String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE); if (!StringUtils.hasLength(refName)) { // A reference to the id of another bean in the same XML file. refName = ele.getAttribute(LOCAL_REF_ATTRIBU...
java
@SuppressWarnings("WeakerAccess") public static NumberField buildRMST(int requestingPlayer, Message.MenuIdentifier targetMenu, CdjStatus.TrackSourceSlot slot, CdjStatus.TrackType trackType) { return new NumberField(((requestingPlayer & 0x0ff) << 24) | ...
java
public static int getIntValue(String primaryKey, String secondaryKey) { Object val = CFG.get(primaryKey); if (val == null) { val = CFG.get(secondaryKey); if (val == null) { throw new SofaRpcRuntimeException("Not found key: " + primaryKey + "/" + secondaryKey); ...
java
public RolloutGroupConditionBuilder errorAction(final RolloutGroupErrorAction action, final String expression) { conditions.setErrorAction(action); conditions.setErrorActionExp(expression); return this; }
java
public void marshall(AudioNormalizationSettings audioNormalizationSettings, ProtocolMarshaller protocolMarshaller) { if (audioNormalizationSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(a...
python
def buildFITSName(geisname): """Build a new FITS filename for a GEIS input image.""" # User wants to make a FITS copy and update it... _indx = geisname.rfind('.') _fitsname = geisname[:_indx] + '_' + geisname[_indx + 1:-1] + 'h.fits' return _fitsname
java
public Attribute removeAttributeWithPrefix(CharSequence prefix, CharSequence name) { for (Iterator<Attribute> it = event.attributes.iterator(); it.hasNext(); ) { Attribute attr = it.next(); if (attr.localName.equals(name) && attr.namespacePrefix.equals(prefix)) { it.remove(); return attr; } ...
python
def deleteFile(self, CorpNum, MgtKeyType, MgtKey, FileID, UserID=None): """ 첨부파일 삭제 args CorpNum : 회원 사업자 번호 MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE'] MgtKey : 파트너 관리번호 UserID : 팝빌 회원아이디 return 처리결...
java
public static AppIdNamespace parseEncodedAppIdNamespace( String encodedAppIdNamespace ) { if ( encodedAppIdNamespace == null ) { throw new IllegalArgumentException( "appIdNamespaceString may not be null" ); } int index = encodedAppIdNamespace.indexOf( NamespaceResources.NAMESPACE_SEP...
java
public boolean validateContentSpec(final ContentSpec contentSpec, final String username) { boolean valid = preValidateContentSpec(contentSpec); if (!postValidateContentSpec(contentSpec, username)) { valid = false; } return valid; }
java
public EClass getGCFARC() { if (gcfarcEClass == null) { gcfarcEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(452); } return gcfarcEClass; }
java
private List<Alert> _getAlertsByOwner(String alertname, PrincipalUser owner, boolean populateMetaFieldsOnly) { List<Alert> result; if (alertname != null && !alertname.isEmpty()) { result = new ArrayList<>(); Alert alert = alertService.findAlertByNameAndOwner(alertname, owner); if (alert != null) { resu...
python
def from_base(cls, base, repo): """ Create a :class:`DXF` object which uses the same host, settings and session as an existing :class:`DXFBase` object. :param base: Existing :class:`DXFBase` object. :type base: :class:`DXFBase` :param repo: Name of the repository to acc...
java
public SVGPath relativeEllipticalArc(double rx, double ry, double ar, double la, double sp, double[] xy) { return append(PATH_ARC_RELATIVE).append(rx).append(ry).append(ar).append(la).append(sp).append(xy[0]).append(xy[1]); }
python
def _compute_distance_scaling(self, C, rrup, mag): """ Returns the distance scaling term """ rscale1 = rrup + C["c2"] * (10.0 ** (C["c3"] * mag)) return -np.log10(rscale1) - (C["c4"] * rrup)
python
def find_nic(nic_id=None, nic_mac_address=None, nic_name=None): """ find the NIC according nic id (prioritary) or name or mac_Address :rtype : object :param nic_id: the NIC id :param nic_mac_address: the NIC mac Address :param nic_name : name :return: found NIC or...
java
@Override public long dynamicQueryCount(DynamicQuery dynamicQuery, Projection projection) { return commerceDiscountRulePersistence.countWithDynamicQuery(dynamicQuery, projection); }
python
def delete_node(self, node_id): """Removes the node identified by node_id from the graph.""" node = self.get_node(node_id) # Remove all edges from the node for e in node['edges']: self.delete_edge_by_id(e) # Remove all edges to the node edges = [edge_id for ...
java
@Override public CPDefinitionSpecificationOptionValue fetchByC_CSOVI( long CPDefinitionId, long CPDefinitionSpecificationOptionValueId, boolean retrieveFromCache) { Object[] finderArgs = new Object[] { CPDefinitionId, CPDefinitionSpecificationOptionValueId }; Object result = null; if (retrieveFromCa...
java
public void setField(String name, MLArray value, int m, int n) { setField(name, value, getIndex(m,n) ); }
python
def get(self, sid): """ Constructs a InstalledAddOnExtensionContext :param sid: The unique Extension Sid :returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionContext :rtype: twilio.rest.preview.marketplace.installed_add_on...
java
protected boolean hasMessageBody(ClientHttpResponse response) throws IOException { HttpStatus responseStatus = response.getStatusCode(); if (responseStatus == HttpStatus.NO_CONTENT || responseStatus == HttpStatus.NOT_MODIFIED) { return false; } long contentLength = response.getHeaders().getContentLength(...
python
def convert(self, type_from, type_to, data): """Parsers data from with one format and composes with another. :param type_from: The unique name of the format to parse with :param type_to: The unique name of the format to compose with :param data: The text to convert """ t...
python
def pack_req(cls, modify_order_op, order_id, price, qty, adjust_limit, trd_env, acc_id, trd_mkt, conn_id): """Convert from user request for place order to PLS request""" from futuquant.common.pb.Trd_ModifyOrder_pb2 import Request req = Request() serial_no = get_unique_id...
python
def add_device_items(self, item, device): """ Add the various items from the device to the node :param str item: item key :param dict device: dictionary containing items """ if item in ('aux', 'console'): self.node['properties'][item] = device[item] e...
java
public static SkbShellArgument[] newArgumentArray(SkbShellArgument ... args){ if(args==null){ return null; } Set<SkbShellArgument> ret = new HashSet<>(); for(SkbShellArgument arg : args){ if(arg!=null){ ret.add(arg); } } return ret.toArray(new SkbShellArgument[args.length]); }
java
private void createTasksForTable(Table table, Collection<IndexSnapshotRequestConfig.PartitionRanges> partitionRanges, Map<Integer, Long> pidToLocalHSIDs, AtomicInteger numTables, ...
java
public void removeTableDef(TableDefinition tableDef) { assert tableDef != null; assert tableDef.getAppDef() == this; m_tableMap.remove(tableDef.getTableName()); }
python
def dumps(obj, mesh_filename=None, *args, **kwargs): # pylint: disable=unused-argument ''' obj: A dictionary mapping names to a 3-dimension array. mesh_filename: If provided, this value is included in the <DataFileName> attribute, which Meshlab doesn't seem to use. TODO Maybe reconstruct this usi...
java
public synchronized <CommandSubclass extends Command> void setupJacksonAnnotatedCommandSerializationAndDeserialization(Class<CommandSubclass> commandSubclassKlass) { checkState(!running); checkState(!initialized); checkState(!setupConversion); RaftRPC.setupJacksonAnnotatedCommandSeriali...
java
public void connectionClosed(ConnectionEvent event) { Object connection = event.getConnectionHandle(); removeConnection(connection); if (cm.getCachedConnectionManager() != null) { cm.getCachedConnectionManager().unregisterConnection(cm, this, connection); } if (connect...
java
private void writeNewClassDesc(ObjectStreamClass classDesc) throws IOException { output.writeUTF(classDesc.getName()); output.writeLong(classDesc.getSerialVersionUID()); byte flags = classDesc.getFlags(); boolean externalizable = classDesc.isExternalizable(); if (ex...
python
def createProduct(self, powerups): """ Create a new L{Product} instance which confers the given powerups. @type powerups: C{list} of powerup item types @rtype: L{Product} @return: The new product instance. """ types = [qual(powerup).decode('ascii') ...
java
public void trainOnInstanceImpl(Instance inst) { accumulatedError= Math.abs(this.prediction(inst)-inst.classValue())*inst.weight() + fadingFactor*accumulatedError; nError=inst.weight()+fadingFactor*nError; // Initialise Perceptron if necessary if (this.initialisePerceptron == true) { //Initialize num...
java
public static Map<QName, String> getAttributes(Node n) { Map<QName, String> map = new LinkedHashMap<QName, String>(); NamedNodeMap m = n.getAttributes(); if (m != null) { final int len = m.getLength(); for (int i = 0; i < len; i++) { Attr a = (Attr) m.item...
java
public void setFile(Element el, String key, Resource value) { if (value != null && value.toString().length() > 0) el.setAttribute(key, value.getAbsolutePath()); }
python
def plot_item(self, funcname): """Plot item""" index = self.currentIndex() if self.__prepare_plot(): key = self.model.get_key(index) try: self.plot(key, funcname) except (ValueError, TypeError) as error: QMessageBox.crit...
java
public static<E> EntryList makeEntryList(final Iterable<E> entries, final StaticArrayEntry.GetColVal<E,ByteBuffer> getter, final StaticBuffer lastColumn, final int limit) { return StaticArrayEntryList.ofByteBuffer(new Iter...
java
@Override public <T> List<T> search(Name base, String filter, SearchControls controls, ContextMapper<T> mapper, DirContextProcessor processor) { assureReturnObjFlagSet(controls); ContextMapperCallbackHandler<T> handler = new ContextMapperCallbackHandler<T>(mapper); search(base, filter, controls, handler, proc...
python
def ehh_decay(h, truncate=False): """Compute the decay of extended haplotype homozygosity (EHH) moving away from the first variant. Parameters ---------- h : array_like, int, shape (n_variants, n_haplotypes) Haplotype array. truncate : bool, optional If True, the return array wi...
java
public static FieldCoordinates coordinates(String parentType, String fieldName) { assertValidName(parentType); assertValidName(fieldName); return new FieldCoordinates(parentType, fieldName); }
python
def list_l3_agent_hosting_routers(self, router, **_params): """Fetches a list of L3 agents hosting a router.""" return self.get((self.router_path + self.L3_AGENTS) % router, params=_params)
java
public static byte[] readAllBytes(java.nio.file.Path path) throws IOException { try (SeekableByteChannel channel = Files.newByteChannel(path); InputStream in = Channels.newInputStream(channel)) { long size = channel.size(); if (size > (long) MAX_BUFFER_SIZE) { throw new OutOfMemoryError("Required array ...
python
def follow(self, something, follow=True): """关注用户、问题、话题或收藏夹 :param Author/Question/Topic something: 需要关注的对象 :param bool follow: True-->关注,False-->取消关注 :return: 成功返回True,失败返回False :rtype: bool """ from .question import Question from .topic import Topic ...
python
def validate(self, raw_data, **kwargs): """The raw_data is returned unchanged.""" super(DateTimeField, self).validate(raw_data, **kwargs) try: if isinstance(raw_data, datetime.datetime): self.converted = raw_data elif self.serial_format is None: ...
java
public void send(Address dst, Object obj) throws Exception { ch.send(dst, obj); }
python
def empty(self): """ Indicator whether DataFrame is empty. True if DataFrame is entirely empty (no items), meaning any of the axes are of length 0. Returns ------- bool If DataFrame is empty, return True, if not return False. See Also ...
java
public static base_response restart(nitro_service client) throws Exception { dbsmonitors restartresource = new dbsmonitors(); return restartresource.perform_operation(client,"restart"); }
java
private static String[] decodeAuthAmqPlain(String response) { Logger logger = LoggerFactory.getLogger(SERVICE_AMQP_PROXY_LOGGER); String[] credentials = null; if ((response != null) && (response.trim().length() > 0)) { ByteBuffer buffer = ByteBuffer.wrap(response.getBytes()...
java
@Deprecated public void pushNotificationClickedEvent(final Bundle extras) { CleverTapAPI cleverTapAPI = weakReference.get(); if(cleverTapAPI == null){ Logger.d("CleverTap Instance is null."); } else { cleverTapAPI.pushNotificationClickedEvent(extras); } }
java
static Object wrapColor4(float red, float green, float blue, float alpha) { ByteBuffer temp = ByteBuffer.allocate(4 * 4); temp.putFloat(red); temp.putFloat(green); temp.putFloat(blue); temp.putFloat(alpha); temp.flip(); return s_wrapperProvider.wrapColor(temp, 0);...
java
public void setGroups(java.util.Collection<GroupIdentifier> groups) { if (groups == null) { this.groups = null; return; } this.groups = new com.amazonaws.internal.SdkInternalList<GroupIdentifier>(groups); }
java
public void getTraceSummaryLine(StringBuilder buff) { // Get the common fields for control messages super.getTraceSummaryLine(buff); buff.append(",reqeustID="); buff.append(getRequestID()); buff.append(",cardinality="); buff.append(getCardinality()); }
python
def title( self ): """ Returns the title for this scene based on its information. :return <str> """ if ( self.currentMode() == XCalendarScene.Mode.Day ): return self.currentDate().toString('dddd, MMMM dd, yyyy') elif ( self.curre...
python
def is_win_python35_or_earlier(): """ Convenience method to determine if the current platform is Windows and Python version 3.5 or earlier. Returns: bool: True if the current platform is Windows and the Python interpreter is 3.5 or earlier; False otherwise. """ retu...
python
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)): '''Return given points rotated around a center point in N dimensions. Angle is list of rotation in radians for each pair of axis. ''' assert isinstance(pts, list) and len(pts) > 0 l_pt_prev = None for pt in pts: assert isinstance(pt, tu...
java
@Override protected <T extends NodeInterface> Set<T> getRelatedNodesReverse(final SecurityContext securityContext, final NodeInterface obj, final Class destinationType, final Predicate<GraphObject> predicate) { Set<T> relatedNodes = new LinkedHashSet<>(); try { final Object source = relation.getSource().get(...
java
public EntityRole getPrebuiltEntityRole(UUID appId, String versionId, UUID entityId, UUID roleId) { return getPrebuiltEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId).toBlocking().single().body(); }
java
public Observable<List<ApplicationInsightsComponentExportConfigurationInner>> createAsync(String resourceGroupName, String resourceName, ApplicationInsightsComponentExportRequest exportProperties) { return createWithServiceResponseAsync(resourceGroupName, resourceName, exportProperties).map(new Func1<ServiceRes...
java
@Override public void writeLong(long v) throws IOException { work[0] = (byte) (0xffL & v); work[1] = (byte) (0xffL & (v >> 8)); work[2] = (byte) (0xffL & (v >> 16)); work[3] = (byte) (0xffL & (v >> 24)); work[4] = (byte) (0xffL & (v >> 32)); work[5] = (byte) (0xffL & (v >> 40)); work[6] = ...
java
public static void applyToText(CharSequence charSequence, Typeface typeface) { applyToText(charSequence, typeface, 0, charSequence.length()); }
java
public static boolean waitForBundleStartup(BundleContext context, Bundle bundle, int secsToWait) { if ((bundle.getState() & Bundle.ACTIVE) == 0) { // Wait for it to start up! if (((bundle.getState() & Bundle.RESOLVED) != 0) || ((bundle.getState() & Bundle.INSTALLED) != 0)) { ...
java
@Override public R visitTypeParameter(TypeParameterElement e, P p) { assert e.getKind() == TYPE_PARAMETER: "Bad kind on TypeParameterElement"; return defaultAction(e, p); }
python
def copytree(source_directory, destination_directory, ignore=None): """ Recursively copy the contents of a source directory into a destination directory. Both directories must exist. This function does not copy the root directory ``source_directory`` into ``destination_directory``. Since `...
java
@Override public Map<K, V> peekAll(final Iterable<? extends K> keys) { Map<K, CacheEntry<K, V>> map = new HashMap<K, CacheEntry<K, V>>(); for (K k : keys) { CacheEntry<K, V> e = execute(k, SPEC.peekEntry(k)); if (e != null) { map.put(k, e); } } return heapCache.convertCacheEn...
java
public void setHighlightSections(final boolean HIGHLIGHT) { if (null == highlightSections) { _highlightSections = HIGHLIGHT; fireTileEvent(REDRAW_EVENT); } else { highlightSections.set(HIGHLIGHT); } }
java
public static Class<?> rawTypeOf(Type type) { if (type instanceof Class) { return (Class) type; } else if (type instanceof ParameterizedType) { return (Class) ((ParameterizedType) type).getRawType(); } else { throw E.unexpected("type not recognized: %s", type)...
python
def factor_schur(z, DPhival, G, A): M, N = G.shape P, N = A.shape """Multiplier for inequality constraints""" l = z[N+P:N+P+M] """Slacks""" s = z[N+P+M:] """Sigma matrix""" SIG = diags(l/s, 0) """Augmented Jacobian""" H = DPhival + mydot(G.T, mydot(SIG, G)) """Factor H"""...
java
public static List<HostAndPort> splitToHostsAndPorts(String hostPortQuorumList) { // split an address hot String[] strings = StringUtils.getStrings(hostPortQuorumList); int len = 0; if (strings != null) { len = strings.length; } List<HostAndPort> list = new ArrayList<HostAndPort>(len); ...
java
public Set<String> getVisibleQueues(PermissionManager permissionManager) { Set<String> ret = new HashSet<String>(); for (QueueDefinition queueDefinition: m_queues) { if (permissionManager.hasPermission(FixedPermissions.ADMIN)) { ret.add(queueDefinition.getName()); continue; } if (!ret.contains(queu...
java
private static void listAllOpenFileDescriptors(PrintWriter writer) throws IOException, InterruptedException { writer.println(); writer.println("All open files"); writer.println("=============="); File[] files = new File("/proc/self/fd").listFiles(); if (files != null) { ...
python
def plugin_valid(self, filepath): """ checks to see if plugin ends with one of the approved extensions """ plugin_valid = False for extension in self.extensions: if filepath.endswith(".{}".format(extension)): plugin_valid = True ...
java
static PublicKey buildX509Key(AlgorithmId algid, BitArray key) throws IOException, InvalidKeyException { /* * Use the algid and key parameters to produce the ASN.1 encoding * of the key, which will then be used as the input to the * key factory. */ DerOutput...
java
public void write(char[] buf) throws IOException { if (writer != null) { writer.write(buf); } else { write(buf, 0, buf.length); } }
python
def collect_table_content(table_bboxes, elems): """ Returns a list of elements that are contained inside the corresponding supplied bbox. """ # list of table content chars table_contents = [[] for _ in range(len(table_bboxes))] prev_content = None prev_bbox = None for cid, c in enume...
java
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); try { Field client = getClass().getDeclaredField("client"); client.setAccessible(true); client.set(this, buildClient(trustSelfSigned)); } catch (NoSuchFieldException e) { throw new Intern...
java
public InternalServerErrorException withErrorDetails(ErrorDetail... errorDetails) { if (this.errorDetails == null) { setErrorDetails(new java.util.ArrayList<ErrorDetail>(errorDetails.length)); } for (ErrorDetail ele : errorDetails) { this.errorDetails.add(ele); } ...
java
void outputComplementDirect(StringBuffer buf) { if (!surrogatesDirect && getContainsBmp() == NONE) buf.append("[\u0000-\uFFFF]"); else { buf.append("[^"); inClassOutputDirect(buf); buf.append(']'); } }
java
private ProposalResponse sendProposalSerially(TransactionRequest proposalRequest, Collection<Peer> peers) throws ProposalException { ProposalException lastException = new ProposalException("ProposalRequest failed."); for (Peer peer : peers) { proposalRequest.submitted = false;...
python
def addPartsToVSLC( self, vslc_id, allele1_id, allele2_id, zygosity_id=None, allele1_rel=None, allele2_rel=None): """ Here we add the parts to the VSLC. While traditionally alleles (reference or variant loci) are traditionally added, you can add any node (such as...
java
private SetterTarget findSetterTarget(String path) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { String[] _accessStack = path.split(REGEXP__CHAR_DOT); if (0 == _accessStack.length) { throw new IllegalArgumentException(path); } int _setterIndex = _accessStack.length -...
java
public static MozuUrl deleteOrderItemUrl(String returnId, String returnItemId) { UrlFormatter formatter = new UrlFormatter("/api/commerce/returns/{orderId}/items/{orderItemId}?updatemode={updateMode}&version={version}"); formatter.formatUrl("returnId", returnId); formatter.formatUrl("returnItemId", returnIte...
python
def from_fp(self, file_pointer, comment_lead=['c']): """ Read a CNF formula from a file pointer. A file pointer should be specified as an argument. The only default argument is ``comment_lead``, which can be used for parsing specific comment lines. :p...
python
def space_time_cluster(catalog, t_thresh, d_thresh): """ Cluster detections in space and time. Use to separate repeaters from other events. Clusters by distance first, then removes events in those groups that are at different times. :type catalog: obspy.core.event.Catalog :param catalog: Cata...
python
def allow_blank(self, form, name): """ Allow blank determines if the form might be completely empty. If it's empty it will result in a None as the saved value for the ForeignKey. """ if self.blank is not None: return self.blank model = form._meta.model ...
python
def _parse_track_spread(self,d1,d2,interp=True,phys=False, simple=_USESIMPLE): """Determine the spread around the track""" if not hasattr(self,'_allErrCovs'): self._determine_stream_spread(simple=simple) okaySpreadR= ['r','vr','vt','z','vz','phi'] ...
python
def find_method(self, decl): """Find class method to call for declaration based on name.""" name = decl.name method = None try: method = getattr(self, u'do_{}'.format( (name).replace('-', '_'))) except AttributeError: if name.s...
java
public boolean barIsEmptyForAllVoices(Bar bar) { for (Object m_voice : m_voices) { Voice v = (Voice) m_voice; if (!v.barIsEmpty(bar)) return false; } return true; }
java
@ObjectiveCName("appendArrayGenericType:types:") public static void appendArrayGenericType(StringBuilder out, Type[] types) { if (types.length == 0) { return; } appendGenericType(out, types[0]); for (int i = 1; i < types.length; i++) { out.append(','); ...
python
def sparse_dot_product_attention(q, k, v, bi, use_map_fn, experts_params): """Sparse multihead self attention. Perform an approximation of the full multihead attention by dispatching the tokens using their keys/values. Thus the attention matrix are only computed each times on a subset of the tokens. Notes: ...
java
private SearchResult<String> searchObjectIds(String indexName, QueryBuilder queryBuilder, int start, int size, List<String> sortOptions, String docType) throws IOException { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(queryBuilder); searchSourc...
python
def make_url(path, protocol=None, hosts=None): """Make an URL given a path, and optionally, a protocol and set of hosts to select from randomly. :param path: The Archive.org path. :type path: str :param protocol: (optional) The HTTP protocol to use. "https://" is used by defau...
python
def comparable(self): """str: comparable representation of the path specification.""" string_parts = [] if self.data_stream: string_parts.append('data stream: {0:s}'.format(self.data_stream)) if self.inode is not None: string_parts.append('inode: {0:d}'.format(self.inode)) if self.locat...
java
public static Container findContainerByIdOrByName( String name, DockerClient dockerClient ) { Container result = null; List<Container> containers = dockerClient.listContainersCmd().withShowAll( true ).exec(); for( Container container : containers ) { List<String> names = Arrays.asList( container.getNames()); ...
python
def top(self, topn, by='counts'): """ Get the top ``topn`` features in the :class:`.FeatureSet`\. Parameters ---------- topn : int Number of features to return. by : str (default: 'counts') How features should be sorted. Must be 'counts' ...
python
def delete_group_action(model, request): """Delete group from database. """ try: groups = model.parent.backend uid = model.model.name del groups[uid] groups() model.parent.invalidate() except Exception as e: return { 'success': False, ...