language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@NullSafe static File[] safeListFiles(File path, FileFilter fileFilter) { return (isDirectory(path) ? path.listFiles(fileFilter) : NO_FILES); }
python
def _addPeptide(self, sequence, proteinId, digestInfo): """Add a peptide to the protein database. :param sequence: str, amino acid sequence :param proteinId: str, proteinId :param digestInfo: dict, contains information about the in silico digest must contain the keys 'missed...
python
def close(self): """Close the transport after all oustanding data has been written.""" if self._closing or self._handle.closed: return elif self._protocol is None: raise TransportError('transport not started') # If the write buffer is empty, close now. Otherwise d...
python
def preprocessing(aws_config, ip_ranges = [], ip_ranges_name_key = None): """ Tweak the AWS config to match cross-service resources and clean any fetching artifacts :param aws_config: :return: """ map_all_sgs(aws_config) map_all_subnets(aws_config) set_emr_vpc_ids(aws_config) #pars...
java
public static <P extends Parser> ParserOption parser(final Class<P> parserClass, final ParserSetup<P> setup) { return new ParserOption(parserClass, setup); }
python
def set_kill_on_exit_mode(bKillOnExit = False): """ Defines the behavior of the debugged processes when the debugging thread dies. This method only affects the calling thread. Works on the following platforms: - Microsoft Windows XP and above. - Wine (Windows Emulator...
java
public void importThisArchive(File file) { String filename = file.getName(); int iIndex = filename.lastIndexOf('.'); if ((iIndex == -1) || (!filename.substring(iIndex).equalsIgnoreCase(".XML"))) return; // This is not an XML file filename = filename.subs...
python
def btc_tx_is_segwit( tx_serialized ): """ Is this serialized (hex-encoded) transaction a segwit transaction? """ marker_offset = 4 # 5th byte is the marker byte flag_offset = 5 # 6th byte is the flag byte marker_byte_string = tx_serialized[2*marker_offset:2*(marker_offset+1)]...
java
public URL getIndexPage() { // In the current impl dependencies are checked first, so the plugin itself // will add the last entry in the getResources result. URL idx = null; try { Enumeration<URL> en = classLoader.getResources("index.jelly"); while (en.hasMoreEle...
python
def values(self): """ Returns a list of values for this field for this instance. It's a list so we can accomodate many-to-many fields. """ # This import is deliberately inside the function because it causes # some settings to be imported, and we don't want to do that at t...
python
def I(self): r"""Returns the set of intermediate states """ return list(set(range(self.nstates)) - set(self._A) - set(self._B))
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { snmp_user_responses result = (snmp_user_responses) service.get_payload_formatter().string_to_resource(snmp_user_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESS...
java
public static double Clamp(double x, DoubleRange range) { return Clamp(x, range.getMin(), range.getMax()); }
java
public Rectangle getTextBounds() { List<TextElement> texts = this.getText(); if (!texts.isEmpty()) { return Utils.bounds(texts); } else { return new Rectangle(); } }
java
void addAll( HashMultimap<K, V> m ) { if( m == this ) { return; } for( Entry<K, List<V>> entry : m.map.entrySet() ) { K key = entry.getKey(); List<V> rules = map.get( key ); if( rules == null ) { rules = new ArrayList<>(); ...
python
def write_hdf5(self, filename, dataset_name=None, info=None, group_name=None): r"""Writes a unyt_array to hdf5 file. Parameters ---------- filename: string The filename to create and write a dataset to dataset_name: string The name of the dataset to crea...
python
def lorem(self, field=None, val=None): """ Returns lorem ipsum text. If val is provided, the lorem ipsum text will be the same length as the original text, and with the same pattern of line breaks. """ if val == '': return '' if val is not None: ...
java
public static TypeTag of(Field field, TypeTag enclosingType) { return resolve(field.getGenericType(), enclosingType, false); }
java
public static void setTextDirection(TextView textView, int textDirection) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { UiCompatNotCrash.setTextDirection(textView, textDirection); } }
java
public static IEntitySerializer getSerializer(final String serializeFormat) throws SerializationException { IEntitySerializer serializer = null; if (isValidSerializeFormat(serializeFormat)) { if (serializeFormat.equalsIgnoreCase(XML_SERIALIZE_FORMAT)) { serializer = new XMLSerializer(); } else if (seriali...
java
@Test public void MPJwtNoMpJwtConfig_mpJwtInWebXML_basicInApp() throws Exception { genericLoginConfigVariationTest( MpJwtFatConstants.LOGINCONFIG_MP_JWT_IN_WEB_XML_SERVLET_BASIC_IN_APP_ROOT_CONTEXT, MpJwtFatConstants.LOGINCONFIG...
java
@Deprecated public Future<Response> generateRequest(String requestType, boolean secure, String endPoint, String data, String type, String codeBase64) throws Exception { return generateRequest(requestType, false, null, null, endPoint, data, type, ""); }
java
static public ModelMetricsBinomial make(Vec targetClassProbs, Vec actualLabels, String[] domain) { Scope.enter(); Vec _labels = actualLabels.toCategoricalVec(); if (domain==null) domain = _labels.domain(); if (_labels == null || targetClassProbs == null) throw new IllegalArgumentException("Missing...
java
public static String encodeToString(byte[] src) { return src == null ? null : Base64.getEncoder().encodeToString(src); }
java
public final ListInstructionsPagedResponse listInstructions(String parent, String filter) { PROJECT_PATH_TEMPLATE.validate(parent, "listInstructions"); ListInstructionsRequest request = ListInstructionsRequest.newBuilder().setParent(parent).setFilter(filter).build(); return listInstructions(request)...
python
def _cache_provider_details(conn=None): ''' Provide a place to hang onto results of --list-[locations|sizes|images] so we don't have to go out to the API and get them every time. ''' DETAILS['avail_locations'] = {} DETAILS['avail_sizes'] = {} DETAILS['avail_images'] = {} locations = avai...
python
def complete_message(buf): "returns msg,buf_remaining or None,buf" # todo: read dollar-length for strings; I dont think I can blindly trust newlines. learn about escaping # note: all the length checks are +1 over what I need because I'm asking for *complete* lines. lines=buf.split('\r\n') if len(lines)<=...
java
public Vec getColumn(int j) { if(j < 0 || j >= cols()) throw new ArithmeticException("Column was not a valid value " + j + " not in [0," + (cols()-1) + "]"); DenseVector c = new DenseVector(rows()); for(int i =0; i < rows(); i++) c.set(i, get(i, j)); return c;...
python
def reflect_ghost(self, p0): """This method creates the ghost point p0', namely p0 reflected along the edge p1--p2, and the point q at the perpendicular intersection of the reflection. p0 _/| \\__ _/ | \\__ / | \\ p1----|q-----...
java
private String getUniqueScriptName(String name, String ext) { if (this.getScriptImpl(name) == null) { // Its unique return name; } // Its not unique, add a suitable index... String stub = name.substring(0, name.length() - ext.length() - 1); int index = 1; do { index++; name = stub + "(...
java
@Deprecated public UpdateInventoryResult update(String orgToken, String requesterEmail, UpdateType updateType, String product, String productVersion, ...
python
def mul(a, b): """ Multiply two values, ignoring None """ if a is None: if b is None: return None else: return b elif b is None: return a return a * b
python
def off(self): """Send OFF command to device.""" self._send_method(StandardSend(self._address, COMMAND_LIGHT_OFF_0X13_0X00), self._off_message_received)
python
def load(): """Read data from a text file on disk.""" # Get the data file relative to this file's location... datadir = os.path.dirname(__file__) filename = os.path.join(datadir, 'angelier_data.txt') data = [] with open(filename, 'r') as infile: for line in infile: # Skip co...
python
def rewrite_schema(r, df, doc=None): """Rebuild the schema for a resource based on a dataframe and re-write the doc""" from metapack.cli.core import write_doc if doc is None: doc = open_source_package() rebuild_schema(doc, r, df) write_doc(doc, doc.ref)
python
def ListHunts(context=None): """List all GRR hunts.""" items = context.SendIteratorRequest("ListHunts", hunt_pb2.ApiListHuntsArgs()) return utils.MapItemsIterator(lambda data: Hunt(data=data, context=context), items)
java
public void setSystemMessageSourceUuid(SIBUuid8 value) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setSystemMessageSourceUuid", value); // Clear the cached MessageHandle cachedMessageHandle = null; // Set the value into the messag...
java
public CQLSSTableWriter rawAddRow(Map<String, ByteBuffer> values) throws InvalidRequestException, IOException { int size = Math.min(values.size(), boundNames.size()); List<ByteBuffer> rawValues = new ArrayList<>(size); for (int i = 0; i < size; i++) { ColumnSpecification spec...
python
def gen_output_fmt_1(self, fmt): """given a single format specifier, get_output_fmt_1() constructs and returns a list of tuples for matching against that specifier. Each element of this list is a tuple (gen_fmt, cvt_fmt, sz) where: gen_fmt is the Python forma...
python
def nanargmax(values, axis=None, skipna=True, mask=None): """ Parameters ---------- values : ndarray axis: int, optional skipna : bool, default True mask : ndarray[bool], optional nan-mask if known Returns -------- result : int The index of max value in specified...
python
def _publish_response(self, slug, message): """Publish a response message for a device Args: slug (string): The device slug that we are publishing on behalf of message (dict): A set of key value pairs that are used to create the message that is sent. """ ...
python
def context_processors_update(context, request): ''' Update context with context_processors from settings Usage: from codenerix.helpers import context_processors_update context_processors_update(context, self.request) ''' for template in settings.TEMPLATES: for context_proces...
java
private static int calculateBinaryString(int[] inputData, StringBuilder binaryString) { EncodeMode last_mode = EncodeMode.NUMERIC; int encoding_method, i, j, read_posn; boolean latch; int remainder, d1, d2, value; String padstring; double weight; int group_val; ...
java
public static final Class resolveTypeVariable(Class invocationClass, Class declaringClass, String typeVarName) { TypeVariable typeVariable = null; for (TypeVariable typeParemeter : declaringClass.getTypeParameters()) { if (typeParemeter.getNa...
python
def get_image_tags(context, instance, options): """ Create a context returning the tags to render an <img ...> element: ``sizes``, ``srcset``, a fallback ``src`` and if required inline styles. """ if hasattr(instance, 'image') and hasattr(instance.image, 'exif'): aspect_ratio = compute_aspec...
java
public int keyOf(double value) { //returns the first key found; there may be more matching keys, however. int i = indexOfValue(value); if (i<0) return Integer.MIN_VALUE; return table[i]; }
python
def push_cluster_configuration(self, scaleioobj, noUpload = False, noInstall= False, noConfigure = False): """ Method push cached ScaleIO cluster configuration to IM (reconfigurations that have been made to cached configuration are committed using IM) Method: POST Attach JSON cluster con...
java
public static Object[] expandArgs(MockitoMethod method, Object[] args) { int nParams = method.getParameterTypes().length; if (args != null && args.length > nParams) args = Arrays.copyOf(args, nParams); // drop extra args (currently -- Kotlin continuation synthetic arg) return expandV...
python
def get_sites_in_sphere(self, pt, r, include_index=False, include_image=False): """ Find all sites within a sphere from the point. This includes sites in other periodic images. Algorithm: 1. place sphere of radius r in crystal and determine minimum supercell (paralle...
python
def get_feed_renderer(engines, name): """ From engine name, load the engine path and return the renderer class Raise 'FeedparserError' if any loading error """ if name not in engines: raise FeedparserError("Given feed name '{}' does not exists in 'settings.FEED_RENDER_ENGINES'".format(n...
python
def rados_parse_df(self, result): ''' Parse the result from ansirunner module and save it as a json object ''' parsed_results = [] HEADING = r".*(pool name) *(category) *(KB) *(objects) *(clones)" + \ " *(degraded) *(unfound) *(rd) *(rd ...
java
public static boolean isDelete(final WebContext context) { return HttpConstants.HTTP_METHOD.DELETE.name().equalsIgnoreCase(context.getRequestMethod()); }
python
def _prepare_by_column_dtype(self, X): """Get distance functions for each column's dtype""" if not isinstance(X, pandas.DataFrame): raise TypeError('X must be a pandas DataFrame') numeric_columns = [] nominal_columns = [] numeric_ranges = [] fit_data = numpy...
java
public void setRPuBase(Integer newRPuBase) { Integer oldRPuBase = rPuBase; rPuBase = newRPuBase; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.FONT_RESOLUTION__RPU_BASE, oldRPuBase, rPuBase)); }
python
def _ge_from_lt(self, other): """Return a >= b. Computed by @total_ordering from (not a < b).""" op_result = self.__lt__(other) if op_result is NotImplemented: return NotImplemented return not op_result
python
def error_pre(f, *args, **kwargs): """Automatically log progress on function entry. Logging value: error. *Logging with values contained in the parameters of the decorated function* Message (args[0]) may be a string to be formatted with parameters passed to the decorated function. Each '{varname}' will...
python
def p_decl_arr(p): """ var_arr_decl : DIM idlist LP bound_list RP typedef """ if len(p[2]) != 1: syntax_error(p.lineno(1), "Array declaration only allows one variable name at a time") else: id_, lineno = p[2][0] SYMBOL_TABLE.declare_array(id_, lineno, p[6], p[4]) p[0] = p[2][...
java
public static <L, R> Tuple<L, R> newTuple (L left, R right) { return new Tuple<L, R>(left, right); }
java
public void interpolateColorValue( ByteBuffer cmapBuffer, int cell ) { cmapBuffer.put(cell == Integer.MAX_VALUE ? blank : getColor((float) cell)); }
java
@Override public Date getConvertedValue() { String dateStr = this.getFirstValue(); if (dateStr != null && !dateStr.trim().isEmpty()) { dateStr = dateStr.trim(); try { return dateFormat.parse(dateStr); } catch (ParseException ex) { ...
java
@Override public EClass getIfcRelConnectsStructuralActivity() { if (ifcRelConnectsStructuralActivityEClass == null) { ifcRelConnectsStructuralActivityEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc4Package.eNS_URI).getEClassifiers().get(538); } return ifcRelConnectsStructuralActivityE...
python
def mask_average(dset,mask): '''Returns average of voxels in ``dset`` within non-zero voxels of ``mask``''' o = nl.run(['3dmaskave','-q','-mask',mask,dset]) if o: return float(o.output.split()[-1])
python
def _traverse_parent_objs(self, goobj_child): """Traverse from source GO up parents.""" child_id = goobj_child.id # mark child as seen self.seen_cids.add(child_id) self.godag.go2obj[child_id] = goobj_child # Loop through parents of child object for parent_obj in g...
java
protected void completeConnectionPreface() throws Http2Exception { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "completeConnectionPreface entry: about to send preface SETTINGS frame"); } FrameSettings settings; // send out a settings frame ...
java
@Override public void addTerm(FilterTerm.Operator op, DB.DateTime date) throws IllegalStateException { final GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date.getValue()); cal.set(MILLISECOND, 0); switch (op) { case GreaterThan: cal.add(Cal...
python
def gradient(self, q, t=0.): """ Compute the gradient of the potential at the given position(s). Parameters ---------- q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like The position to compute the value of the potential. If the ...
java
public static DatabaseVendor detectDbVendor(Connection conn) throws SQLException { DatabaseMetaData dmd = conn.getMetaData(); String dpn = dmd.getDatabaseProductName(); if (StringUtils.equalsAnyIgnoreCase("MySQL", dpn)) { return DatabaseVendor.MYSQL; } if (StringUtils...
python
def getlanguages(self, event): """Compile and return a human readable list of registered translations""" self.log('Client requests all languages.', lvl=verbose) result = { 'component': 'hfos.ui.clientmanager', 'action': 'getlanguages', 'data': language_token_...
java
private static void checkHttpDataSize(HttpData data) { try { data.checkSize(data.length()); } catch (IOException ignored) { throw new IllegalArgumentException("Attribute bigger than maxSize allowed"); } }
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case BasePackage.SF__NUMBER: return number != NUMBER_EDEFAULT; case BasePackage.SF__OFFSET: return offset != OFFSET_EDEFAULT; case BasePackage.SF__ID: return id != ID_EDEFAULT; case BasePackage.SF__LENGTH: return length...
java
ChildDrawable addLayer(Drawable dr, int[] themeAttrs, int id, int left, int top, int right, int bottom) { final ChildDrawable childDrawable = createLayer(dr); childDrawable.mId = id; childDrawable.mThemeAttrs = themeAttrs; if (Build.VERSION.SDK_INT >= Build.VER...
java
private void addRootElement() { Node root = helper.getRoot(); if (root != null) result.add(root); }
java
public ClassLoader getSiteClassLoader (int siteId) throws IOException { // synchronize on the lock to ensure that only one thread per site // is concurrently executing synchronized (getLock(siteId)) { // see if we've already got one ClassLoader loader = _loade...
python
def delete(cls, session, record, endpoint_override=None, out_type=None): """Delete a record. Args: session (requests.sessions.Session): Authenticated session. record (helpscout.BaseModel): The record to be deleted. endpoint_override (str, optional): Override the defa...
python
def parseArgs(): """Read arguments""" parser = argparse.ArgumentParser() parser.add_argument("-names", "-n", help=".txt file of taxonomic names") parser.add_argument("-datasource", "-d", help="taxonomic datasource by \ which names will be resolved (default NCBI)") parser.add_argument("-taxonid", "-t...
java
public static Object findResult(Object self, Object defaultResult, Closure condition) { Object result = findResult(self, condition); if (result == null) return defaultResult; return result; }
java
public static <T> Iterable<T> takeWhile(final Iterable<? extends T> iterable, final Function1<? super T, Boolean> predicate) { if (iterable == null) throw new NullPointerException("iterable"); if (predicate == null) throw new NullPointerException("predicate"); return new Iterable<T>() { @Override publ...
python
def srfcss(code, bodstr, srflen=_default_len_out): """ Translate a surface ID code, together with a body string, to the corresponding surface name. If no such surface name exists, return a string representation of the surface ID code. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/...
java
public void setOutputArtifacts(java.util.Collection<Artifact> outputArtifacts) { if (outputArtifacts == null) { this.outputArtifacts = null; return; } this.outputArtifacts = new java.util.ArrayList<Artifact>(outputArtifacts); }
python
def update_state(self, iid, state): """ Set a custom state of the marker :param iid: identifier of the marker to set the state of :type iid: str :param state: supports "active", "hover", "normal" :type state: str """ if state not in ["normal", "hover", "a...
java
public static void debug(final Object message) { if (MINIMUM_LEVEL_COVERS_DEBUG) { provider.log(STACKTRACE_DEPTH, null, Level.DEBUG, null, message, (Object[]) null); } }
java
@SuppressWarnings("unchecked") public <TO> ChainedTransformer<I, TO> chain(Transformer<O, TO> transformer) { if (transformer != null) { transformers.add(transformer); } return (ChainedTransformer<I, TO>) this; }
python
def new_account( self, account_cookie=None, init_cash=1000000, market_type=MARKET_TYPE.STOCK_CN, *args, **kwargs ): """创建一个新的Account Keyword Arguments: account_cookie {[type]} -- [description] (default: {None}) ...
python
def _data_flow_chain(self): """ Get a list of all elements in the data flow graph. The first element is the original source, the next one reads from the prior and so on and so forth. Returns ------- list: list of data sources """ if self.data_producer is...
python
def process(self, tup): """Process steps: 1. Stream in (term, timestamp). 2. Perform :meth:`~birding.search.SearchManager.search` on term. 3. Emit (term, timestamp, search_result). """ term, timestamp = tup.values if term not in self.term_shelf: self....
java
public void subscribe(Object identifier) { final long id = Thread.currentThread().getId(); queues.put(id, new ConcurrentLinkedQueue<T>()); if (identifier != null) { if (subscriberIdentifiers == null) { subscriberIdentifiers = new ConcurrentHashMap<>(); } ...
java
public MatchIterator get(long key, int hashCode) { int bucket = hashCode & numBucketsMask; int bucketOffset = bucket << 4; MemorySegment segment = buckets[bucketOffset >>> segmentSizeBits]; int segOffset = bucketOffset & segmentSizeMask; while (true) { long address = segment.getLong(segOffset + 8); if...
java
private Label getTryFixedEndLabel(LocalVariableScopeData scope, TryCatchBlockLabels enclosingTry) { if (enclosingTry == null) { return scope.labels.end; } else { if (getIndex(enclosingTry.handler) < getIndex(scope.labels.end)) { return enclosingTry.handler; } else { return scope.labels.end; } ...
python
def _consolidate_auth(ssh_password=None, ssh_pkey=None, ssh_pkey_password=None, allow_agent=True, host_pkey_directories=None, logger=None): """ Get sure authentication inform...
java
public JFreeChartRender setRangeAxis(double lowerBound, double upperBound) { ValueAxis valueAxis = getPlot().getRangeAxis(); valueAxis.setUpperBound(upperBound); valueAxis.setLowerBound(lowerBound); return this; }
python
def insert_execution_history(self, parent, execution_history, is_root=False): """Insert a list of history items into a the tree store If there are concurrency history items, the method is called recursively. :param Gtk.TreeItem parent: the parent to add the next history item to :param ...
python
def remove_node_attributes(G: nx.DiGraph, attributes: Union[str, Iterable[str]]): """ Return a copy of the graph with the given attributes deleted from all nodes. """ G = G.copy() for _, data in G.nodes(data=True): for attribute in setwrap(attributes): if attribute in data: ...
java
@Override public Response update(String CorpNum, String MgtKey, Cashbill cashbill, String UserID) throws PopbillException { if (MgtKey == null || MgtKey.isEmpty()) throw new PopbillException(-99999999, "관리번호가 입력되지 않았습니다."); String PostData = toJsonString(cashbill); return httppost("/Cashbill/"+Mg...
java
private static DMatrix csc(Chunk[] chunks, int weight, long nRows, DataInfo di, float[] resp, float[] weights) throws XGBoostError { return csc(chunks, weight, null, null, null, null, nRows, di, resp, weights); }
python
def get_active_terms_ids(): """Returns a list of the IDs of of all terms and conditions""" active_terms_ids = cache.get('tandc.active_terms_ids') if active_terms_ids is None: active_terms_dict = {} active_terms_ids = [] active_terms_set = TermsAndConditions....
java
public synchronized void addToJoin(ISynchronizationPoint<? extends TError> sp) { nbToJoin++; sp.listenInline(new Runnable() { @Override public void run() { if (sp.isCancelled()) cancel(sp.getCancelEvent()); else if (sp.hasError()) error(sp.getError()); else joined(); }...
python
def exists(self, name): """ does the key exist in redis? :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.exists(self.redis_key(name))
java
public static void validateBindParametersTypes(Parameters parameters) { final Iterator<Parameter> it = parameters.iterator(); while (it.hasNext()) { final Parameter param = it.next(); final Class<?> paramType = param.getType(); if (!(param.isSpecialParameter() || SupportedCoreTypes .isSupported(para...
python
def p_boolean_literal(self, p): """boolean_literal : TRUE | FALSE """ p[0] = self.asttypes.Boolean(p[1]) p[0].setpos(p)
java
public ByteBuffer flattenPlanArrayToBuffer() throws IOException { int size = 0; // sizeof batch ParameterSet userParamCache = null; if (userParamSet == null) { userParamCache = ParameterSet.emptyParameterSet(); } else { Object[] typedUserParams = new Object[userP...