language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private Renderer recycle(View convertView, T content) { Renderer renderer = (Renderer) convertView.getTag(); renderer.onRecycle(content); return renderer; }
python
def feature_list(): """ Check the library for compile-time features. The list of features are maintained in libinfo.h and libinfo.cc Returns ------- list List of :class:`.Feature` objects """ lib_features_c_array = ctypes.POINTER(Feature)() lib_features_size = ctypes.c_size_t() ...
java
@Override public ExtendedSet<T> intersection(Collection<? extends T> other) { ExtendedSet<T> clone = clone(); clone.retainAll(other); return clone; }
java
public static String getConfPath() { String classpath = CommonUtils.class.getResource("/").getPath(); String confPath = classpath + "../conf/"; if (new File(confPath).exists()) { return confPath; } else { return classpath; } }
java
public BoxRequestsShare.GetCollaborationInfo getInfoRequest(String collaborationId) { BoxRequestsShare.GetCollaborationInfo collab = new BoxRequestsShare.GetCollaborationInfo(collaborationId, getCollaborationInfoUrl(collaborationId), mSession); return collab; }
java
public void saveMapping(final Writer out) throws IOException { for ( final Iterator it = this.mapping.getEntries().iterator(); it.hasNext(); ) { out.write( it.next().toString() ); out.write( "\n" ); } }
python
def as_dict(self): """ Json-serializable dict representation of DefectEntry """ d = {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "defect": self.defect.as_dict(), "uncorrected_energy": self.uncorrected_energy, ...
java
public final int getIgnoreCase(String key) { if (null == key) return INVALID_KEY; for (int i = 0; i < m_firstFree; i++) { if (m_map[i].equalsIgnoreCase(key)) return m_values[i]; } return INVALID_KEY; }
python
def _set_isis(self, v, load=False): """ Setter method for isis, mapped from YANG variable /routing_system/router/isis (container) If this variable is read-only (config: false) in the source YANG file, then _set_isis is considered as a private method. Backends looking to populate this variable should...
python
def _validate_signature_compatibility(self, boxes): """Validate the file signature and compatibility status.""" # Check for a bad sequence of boxes. # 1st two boxes must be 'jP ' and 'ftyp' if boxes[0].box_id != 'jP ' or boxes[1].box_id != 'ftyp': msg = ("The first box must...
python
def on(self): """Send the On command to an X10 device.""" msg = X10Send.unit_code_msg(self.address.x10_housecode, self.address.x10_unitcode) self._send_method(msg) msg = X10Send.command_msg(self.address.x10_housecode, ...
java
public static String getBacktrace(JUnitTestData testMethod) { StringBuilder stackTrace = new StringBuilder(); Throwable throwable = testMethod.getFailException(); if (throwable != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw);...
java
public Table gethTable(final String tableName) throws IOException { return connection.getTable(TableName.valueOf(tableName)); }
java
@Override public <T extends ApiUser> List<T> in(ApiRoom room) { Room sfsRoom = CommandUtil.getSfsRoom(room, extension); validateRoom(sfsRoom, room); return CommandUtil.getApiUserList(sfsRoom.getUserList()); }
java
@Override public boolean removeJob(JobKey jobKey, Jedis jedis) throws JobPersistenceException { final String jobHashKey = redisSchema.jobHashKey(jobKey); final String jobBlockedKey = redisSchema.jobBlockedKey(jobKey); final String jobDataMapHashKey = redisSchema.jobDataMapHashKey(jobKey); ...
java
public void setInvocationHandler(Object proxy, InvocationHandler handler) { Field field = getInvocationHandlerField(); try { field.set(proxy, handler); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { ...
java
static double run(int num_threads) { final double membw[] = new double[num_threads]; Thread[] threads = new Thread[num_threads]; for (int t=0;t<num_threads;++t) { final int thread_num = t; threads[t] = new Thread() { public void run() { MemoryBandwidth l = new MemoryBandwidth(...
java
public static PageFlowController getNestingPageFlow( HttpServletRequest request, ServletContext servletContext ) { PageFlowStack jpfStack = PageFlowStack.get( request, servletContext, false ); if ( jpfStack != null && ! jpfStack.isEmpty() ) { PageFlowController top = jpf...
python
def get_peb_address(self): """ Returns a remote pointer to the PEB. @rtype: int @return: Remote pointer to the L{win32.PEB} structure. Returns C{None} on error. """ try: return self._peb_ptr except AttributeError: hProcess = s...
java
@Override public void close() { cache.close(); if (!getRuntimeConfiguration().getResourcePools().getPoolForResource(ResourceType.Core.DISK).isPersistent()) { try { diskPersistenceService.destroy(id); } catch (CachePersistenceException e) { logger.debug("Unable to clear persistence ...
java
public static boolean copy(File src, FileSystem dstFS, Path dst, boolean deleteSource, Configuration conf) throws IOException { dst = checkDest(src.getName(), dstFS, dst, false); if (src.isDirectory()) { if (!dstFS.mkd...
python
def array(self): """ return the underlying numpy array """ return np.linspace(self.start, self.stop, self.num, self.endpoint)
java
public Quantile combine(final Quantile other) { if (Double.compare(_quantile, other._quantile) != 0) { throw new IllegalArgumentException(format( "Can't perform combine, the quantile are not equal: %s != %s", _quantile, other._quantile )); } _samples += other._samples; if (_quantile == 0.0) { ...
python
def getBothEdges(self, label=None): """Gets all the edges of the node. If label parameter is provided, it only returns the edges of the given label @params label: Optional parameter to filter the edges @returns A generator function with the incoming edges""" if label: ...
python
def write_file(path, data): """Writes data to specified path.""" with open(path, 'w') as f: log.debug('setting %s contents:\n%s', path, data) f.write(data) return f
python
def unregister_handle_func(self, _handle_func_name, topic): """ 注销handle_func """ handler_list = self._handle_funcs.get(topic, []) for i, h in enumerate(handler_list): if h is _handle_func_name or h.__name__ == _handle_func_name: handler_list.pop(i) if self._...
java
public static int generateDataset(String file, String test, String standard){ int textCharCount=0; try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"utf-8")); BufferedWriter testWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStr...
python
def to_string(self): """ Return the current NDEF as a string (always 64 bytes). """ data = self.ndef_str if self.ndef_type == _NDEF_URI_TYPE: data = self._encode_ndef_uri_type(data) elif self.ndef_type == _NDEF_TEXT_TYPE: data = self._encode_ndef_t...
java
public void marshall(Resource resource, ProtocolMarshaller protocolMarshaller) { if (resource == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resource.getType(), TYPE_BINDING); protocol...
java
private void addHomozygousGenotype(Variant variant, int numAllele, String[] alternateAlleles, VariantStats stats, String[] homCounts) { if (homCounts.length == alternateAlleles.length) { for (int i = 0; i < homCounts.length; i++) { Integer alleles[] = new Integer[2]; ...
java
static void setEmpty(final WritableMemory wmem) { int flags = wmem.getByte(FLAGS_BYTE) & 0XFF; flags |= EMPTY_FLAG_MASK; wmem.putByte(FLAGS_BYTE, (byte) flags); }
python
def calc_max_flexural_wavelength(self): """ Returns the approximate maximum flexural wavelength This is important when padding of the grid is required: in Flexure (this code), grids are padded out to one maximum flexural wavelength, but in any case, the flexural wavelength is a good character...
java
public static CommerceWishListItem fetchByCW_CP_First( long commerceWishListId, long CProductId, OrderByComparator<CommerceWishListItem> orderByComparator) { return getPersistence() .fetchByCW_CP_First(commerceWishListId, CProductId, orderByComparator); }
python
def mknod(self, req, parent, name, mode, rdev): """Create file node Valid replies: reply_entry reply_err """ self.reply_err(req, errno.EROFS)
java
public void marshall(GetIntentVersionsRequest getIntentVersionsRequest, ProtocolMarshaller protocolMarshaller) { if (getIntentVersionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getInte...
java
@Override public boolean replace ( TypeK key, TypeV oldValue, TypeV newValue ) { return Objects.equals(putIfMatch( key, newValue, oldValue ), oldValue); }
java
@Override public void terminateMachine( TargetHandlerParameters parameters, String machineId ) throws TargetException { this.logger.fine( "Terminating machine " + machineId ); ComputeService computeService = jcloudContext( parameters.getTargetProperties()); computeService.destroyNode( machineId ); computeServ...
java
protected void addMsgToLogHandler(String msgId, String handlerId) { Set<String> logHandlerIdSet = getOrCreateLogHandlerIdSet(msgId); logHandlerIdSet.add(handlerId); }
java
public final Observable<Float> sumFloat(Func1<? super T, Float> valueExtractor) { return OperatorSum.sumAtLeastOneFloats(o.map(valueExtractor)); }
java
public static double elementMinAbs( DMatrix5 a ) { double min = Math.abs(a.a1); double tmp = Math.abs(a.a1); if( tmp < min ) min = tmp; tmp = Math.abs(a.a2); if( tmp < min ) min = tmp; tmp = Math.abs(a.a3); if( tmp < min ) min = tmp; tmp = Math.abs(a.a4); if( tmp < min ) min = tm...
java
public static String getThreadName(String name){ if(name==null || name.isEmpty()){ return SD_THREAD_PREFIX + nextIndex(); } return SD_THREAD_PREFIX + name + "_" + nextIndex(); }
python
def _CreateStyleForRoute(self, doc, route): """Create a KML Style element for the route. The style sets the line colour if the route colour is specified. The line thickness is set depending on the vehicle type. Args: doc: The KML Document ElementTree.Element instance. route: The transitfee...
python
def save(self, *args, **kwargs): """ Custom save method does the following things: * converts geometry collections of just 1 item to that item (eg: a collection of 1 Point becomes a Point) * intercepts changes to status and fires node_status_changed signal * set defau...
java
public void removeAttributeSilent(String attributeName) { CmsEntityAttribute attr = getAttribute(attributeName); if (attr != null) { if (attr.isSimpleValue()) { m_simpleAttributes.remove(attributeName); } else { for (CmsEntity child : attr....
python
def state_histogram(rho, ax=None, title="", threshold=0.001): """ Visualize a density matrix as a 3d bar plot with complex phase encoded as the bar color. This code is a modified version of `an equivalent function in qutip <http://qutip.org/docs/3.1.0/apidoc/functions.html#qutip.visualization.matri...
python
def get_in_seg_vlan(cls, tenant_id): """Retrieves the IN Seg, VLAN, mob domain. """ if tenant_id not in cls.serv_obj_dict: LOG.error("Fabric not prepared for tenant %s", tenant_id) return None, None tenant_obj = cls.serv_obj_dict.get(tenant_id) return tenant_obj.g...
python
def _breakend_orientation(strand1, strand2): """Convert BEDPE strand representation of breakpoints into VCF. | strand1 | strand2 | VCF | +----------+----------+--------------+ | + | - | t[p[ ]p]t | | + | + | t]p] t]p] | | - | - | [p[t [...
java
private void checkArgumentsMatchParameters( Node call, FunctionType functionType, Iterator<Node> arguments, Iterator<Node> parameters, int firstParameterIndex) { int spreadArgumentCount = 0; int normalArgumentCount = firstParameterIndex; boolean checkArgumentTypeAgainstParamet...
python
def changeTo(self, path): '''change value Args: path (str): the new environment path ''' dictionary = DictSingle(Pair('PATH', StringSingle(path))) self.value = [dictionary]
python
def search(self, kw): '''Takes a keyword and returns the search results. Works for boxes only? Args: kw keyword (str) to search for. return (code, list(dicts)) ''' if not kw: return requests.codes.bad_request, None code, data = self._req('get', self.search_uri + kw) return code, data
java
public void delete(String bucketName, List<KeyVersion> objects) { ReactiveSeq.fromList(objects) .grouped(1000) .forEach(l -> { DeleteObjectsRequest req = new DeleteObjectsRequest( ...
java
public Vector3d normalizedPositiveX(Vector3d dir) { double dy = y + y; double dz = z + z; dir.x = -y * dy - z * dz + 1.0; dir.y = x * dy - w * dz; dir.z = x * dz + w * dy; return dir; }
java
private void populateMetaData() throws SQLException { m_meta.clear(); ResultSetMetaData meta = m_rs.getMetaData(); int columnCount = meta.getColumnCount() + 1; for (int loop = 1; loop < columnCount; loop++) { String name = meta.getColumnName(loop); Integer type = Inte...
python
def ungroup_emoji(toks): "Ungroup emojis" res = [] for tok in toks: if emoji.emoji_count(tok) == len(tok): for char in tok: res.append(char) else: res.append(tok) return res
java
public void updateOptions(Map<String, Object> newOptions, Map<String, Object> changedOptions, Map<String, Object> deletedOptions) throws ProvisioningApiException { try { OptionsPutResponseStatusSuccess resp = optionsApi.optionsPut( new OptionsPut() ...
java
public static void nv21ToGray(byte[] dataNV, GrayU8 output) { final int yStride = output.width; // see if the whole thing can be copied as one big block to maximize speed if( yStride == output.width && !output.isSubimage() ) { System.arraycopy(dataNV,0,output.data,0,output.width*output.height); } else { ...
java
public static void main(final String[] args) { if (args.length > 0 && (args[0].equals("--version") || args[0].equals("-v"))) out(getLibraryHeader(false)); else { out(getLibraryHeader(true)); out(sep + "Supported protocols: " + supportedProtocols().collect(joining(", "))); } }
python
def set_state(block, state): """ Sets the user state, generally used for syntax highlighting. :param block: block to modify :param state: new state value. :return: """ if block is None: return user_state = block.userState() if user_sta...
java
private void addCommonCacheKeyParts(StringBuilder builder) { builder.append("kind=").append(getKind()); List<FilterPredicate> predicates = query.getFilterPredicates(); if (predicates.size() > 0) { builder.append(",pred=").append(predicates); } }
java
@Override public CreateServiceResult createService(CreateServiceRequest request) { request = beforeClientExecution(request); return executeCreateService(request); }
java
private void applyChanges(PrintWriter out, Reconfigurable reconf, HttpServletRequest req) throws IOException, ReconfigurationException { Configuration oldConf = reconf.getConf(); Configuration newConf = new Configuration(); if (reconf instanceof ReconfigurableBase) ((R...
python
def cep(numero): """Valida um número de CEP. O número deverá ser informado como uma string contendo 8 dígitos numéricos. Se o número informado for inválido será lançada a exceção :exc:`NumeroCEPError`. .. warning:: Qualquer string que contenha 8 dígitos será considerada como um CEP vál...
python
def score(self, X_test, y=None): """Computes the score between cov/prec of sample covariance of X_test and X via 'score_metric'. Note: We want to maximize score so we return the negative error. Parameters ---------- X_test : array-like, shape = [n_samples, n_features] ...
java
public ByteBuffer getData() { if (this.buffer == null) { throw new IllegalStateException("ByteBuffer must have data before it is ready for use."); } final ByteBuffer copy = CausticUtil.createByteBuffer(buffer.capacity()); buffer.rewind(); copy.put(buffer); cop...
java
public Set<T> inEdges(int vertex) { // REMINDER: this is probably best wrapped with yet another decorator // class to avoid the O(n) penality of iteration over all the edges Set<T> edges = getAdjacencyList(vertex); if (edges.isEmpty()) return Collections.<T>emptySet(); ...
python
def _get_metadata_as_string(self): """Get the metadata as SOFT formatted string.""" metalist = [] for metaname, meta in iteritems(self.metadata): message = "Single value in metadata dictionary should be a list!" assert isinstance(meta, list), message for data ...
python
def get_argument_parser(): """Create the argument parser for the script. Parameters ---------- Returns ------- `argparse.ArgumentParser` The arguemnt parser. """ desc = 'Generate a sample sheet based on a GEO series matrix.' parser = cli.get_argument_parser(desc=desc) ...
java
public <T extends View> T getView(Class<T> classToFilterBy, int index) { return waiter.waitForAndGetView(index, classToFilterBy); }
java
public static String convertToBase64(String source) { if (source == null) { return null; } return Base64.encodeBase64URLSafeString(StringUtils.getBytesUtf8(source)); }
java
private RuntimeException launderException(final Throwable throwable) { if (throwable instanceof RuntimeException) { return (RuntimeException) throwable; } else if (throwable instanceof Error) { throw (Error) throwable; } else { throw new IllegalStateException(...
python
def aes(encrypt, key, data): """ One-pass AES-256-CBC used in ProcessData. Zero IV (don't panic, IV-like random nonce is included in plaintext in the first block in ProcessData). Does not use padding (data has to be already padded). :param encrypt: :param key: :param data: :return: ...
java
public static String extractValueByName(List<MemberValuePair> pairs, String name){ for(MemberValuePair pair : pairs){ if(pair.getName().equals(name)){ return pair.getValue().toString(); } } return null; }
python
def recursively_preempt_states(self): """Preempt the state """ self.preempted = True self.paused = False self.started = False
java
public FunctionList name(final String name) { return filter(new Filter() { public boolean keep(Function m) { return m.getName().equals(name); } }); }
java
protected double[] getDialogDimensions(String message, VaadinConfirmDialog.ContentMode style) { // Based on Reindeer style: double chrW = 0.51d; double chrH = 1.5d; double length = message != null? chrW * message.length() : 0; double rows = Math.ceil(length / MAX_WID...
java
public void setPrivateIpAddresses(java.util.Collection<PrivateIpAddressDetails> privateIpAddresses) { if (privateIpAddresses == null) { this.privateIpAddresses = null; return; } this.privateIpAddresses = new java.util.ArrayList<PrivateIpAddressDetails>(privateIpAddresses...
python
def is_conflicting(self): """If installed version conflicts with required version""" # unknown installed version is also considered conflicting if self.installed_version == self.UNKNOWN_VERSION: return True ver_spec = (self.version_spec if self.version_spec else '') r...
python
def update_attachment(self, volumeID, attachmentID, metadata): '''update an existing attachment the given metadata dict will be merged with the old one. only the following fields could be updated: [name, mime, notes, download_count] ''' log.debug('updating metadata of at...
python
async def stop_slaves(self, timeout=1): """Stop all the slaves by sending a stop-message to their managers. :param int timeout: Timeout for connecting to each manager. If a connection can not be made before the timeout expires, the resulting error for that particular...
java
@Override public T read(final JsonReader in) throws IOException { final JsonElement tree = elementAdapter.read(in); if (tree.isJsonObject()) { for (Map.Entry<String, List<String>> entry : serializedNameMethods.entrySet()) { final String fieldName = entry.getKey(); final List<String> alte...
python
def get_archs(libname): """ Return architecture types from library `libname` Parameters ---------- libname : str filename of binary for which to return arch codes Returns ------- arch_names : frozenset Empty (frozen)set if no arch codes. If not empty, contains one or more ...
python
def get_default_widget(): """ Get the default widget or the widget defined in settings """ default_widget = forms.Textarea if hasattr(settings, 'BLEACH_DEFAULT_WIDGET'): default_widget = load_widget(settings.BLEACH_DEFAULT_WIDGET) return default_widget
java
public final int compareTo(E o) { Enum<?> other = (Enum<?>)o; Enum<E> self = this; if (self.getClass() != other.getClass() && // optimization self.getDeclaringClass() != other.getDeclaringClass()) throw new ClassCastException(); return self.ordinal - other.ordinal...
java
public static boolean isValidFqcn(String str) { if (isNullOrEmpty(str)) { return false; } final String[] parts = str.split("\\."); if (parts.length < 2) { return false; } for (String part : parts) { if (!isValidJavaIdentifier(part)) { return false; } } ret...
python
def deadends(self): """ Get all CFGNodes that has an out-degree of 0 :return: A list of CFGNode instances :rtype: list """ if self.graph is None: raise AngrCFGError('CFG hasn\'t been generated yet.') deadends = [i for i in self.graph if self.graph.o...
java
private void syncContext(boolean isInit) { // jmeter context synchronisation JMeterContext current = JMeterContextService.getContext(); JMeterContext ctx = this.getThreadContext(); if (isInit) { current.setCurrentSampler(ctx.getCurrentSampler()); current.setEngine(ctx.getEngine());...
python
def open(self, mode=None): """ Open the container file. Args: mode (str): Either 'r' for read-only, 'w' for truncate and write or 'a' for append. (default: 'a'). If ``None``, uses ``self.mode``. """ if mode is None: ...
java
public ApiResponse<DeviceTypePricingTiersEnvelope> getThePricingTiersWithHttpInfo(String dtid, Integer version) throws ApiException { com.squareup.okhttp.Call call = getThePricingTiersValidateBeforeCall(dtid, version, null, null); Type localVarReturnType = new TypeToken<DeviceTypePricingTiersEnvelope>()...
java
public long getWindowStartTimeForTime(long time) { //Calculate aggregate offset: aggregate offset is due to both timezone and manual offset long aggregateOffset = (timeZone.getOffset(time) + this.offsetAmountMilliseconds) % this.windowSizeMilliseconds; return (time + aggregateOffset) - (time +...
java
@Indexable(type = IndexableType.REINDEX) @Override public CPDefinitionVirtualSetting updateCPDefinitionVirtualSetting( CPDefinitionVirtualSetting cpDefinitionVirtualSetting) { return cpDefinitionVirtualSettingPersistence.update(cpDefinitionVirtualSetting); }
python
def get_closest_points(self, mesh): """ Find closest point of this mesh for each point in the other mesh :returns: :class:`Mesh` object of the same shape as `mesh` with closest points from this one at respective indices. """ min_idx = cdist(self.xyz, mesh...
java
@Nonnull public static LongToDoubleFunction longToDblFunctionFrom(Consumer<LongToDoubleFunctionBuilder> buildingFunction) { LongToDoubleFunctionBuilder builder = new LongToDoubleFunctionBuilder(); buildingFunction.accept(builder); return builder.build(); }
java
public final void mEscapeSequence() throws RecognitionException { try { // BELScript.g:315:24: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\"' | '\\'' | '\\\\' ) | UnicodeEscape | OctalEscape ) int alt15=3; int LA15_0 = input.LA(1); if ( (LA15_0=='\\') ) { ...
java
protected void processFormLayout(FormInstance topLevelForm, FormInstance form, Map<String, Object> inputs, Map<String, Object> outputs, String layoutTemplate, StringBuilder jsonTemplate, boolean wrapJson, List<String> scriptDataLi...
java
@SuppressWarnings("unchecked") E removeAt(int i) { // assert i >= 0 && i < size; modCount++; int s = --size; if (s == i) // removed last element queue[i] = null; else { E moved = (E) queue[s]; queue[s] = null; siftDown(i, moved)...
python
def iscomplete(rawmessage): """Test if the raw message is a complete message.""" if len(rawmessage) < 2: return False if rawmessage[0] != 0x02: raise ValueError('message does not start with 0x02') messageBuffer = bytearray() filler = bytearray(30) messageBuffer.extend(rawmessag...
java
@Override public CommerceVirtualOrderItem fetchCommerceVirtualOrderItemByUuidAndGroupId( String uuid, long groupId) { return commerceVirtualOrderItemPersistence.fetchByUUID_G(uuid, groupId); }
python
def obfn_dfd(self): r"""Compute data fidelity term :math:`(1/2) \| D \mathbf{x} - \mathbf{s} \|_2^2`. """ return 0.5*np.linalg.norm((self.D.dot(self.obfn_fvar()) - self.S))**2
python
def _set_is_address_family_v6(self, v, load=False): """ Setter method for is_address_family_v6, mapped from YANG variable /isis_state/router_isis_config/is_address_family_v6 (container) If this variable is read-only (config: false) in the source YANG file, then _set_is_address_family_v6 is considered as...
python
def standby(df, resolution='24h', time_window=None): """ Compute standby power Parameters ---------- df : pandas.DataFrame or pandas.Series Electricity Power resolution : str, default='d' Resolution of the computation. Data will be resampled to this resolution (as mean) before ...