language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public LambdaDslJsonArray or(Object value, MatchingRule... rules) { pactArray.or(value, rules); return this; }
python
def _generate_config(self): """Generate a configuration that can be sent to the Hottop roaster. Configuration settings need to be represented inside of a byte array that is then written to the serial interface. Much of the configuration is static, but control settings are also included ...
java
public void setGlobalSecondaryIndexes(java.util.Collection<GlobalSecondaryIndexDescription> globalSecondaryIndexes) { if (globalSecondaryIndexes == null) { this.globalSecondaryIndexes = null; return; } this.globalSecondaryIndexes = new java.util.ArrayList<GlobalSecondary...
python
def build_versioned(self, id, **kwargs): """ Builds the configurations for the Specified Set with an option to specify exact revision of a BC This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function ...
python
def _transform(self, X): """Asssume X contains only categorical features. Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. """ X = self._matrix_adjust(X) X = check_array(X, accept_spar...
java
public static NodeImpl createContainerElementNode(final String name, final NodeImpl parent) { return new NodeImpl( // name, // parent, // false, // null, // null, // ElementKind.CONTAINER_ELEMENT, // EMPTY_CLASS_ARRAY, // null, // null, // ...
java
boolean removeObserver(ApptentiveNotificationObserver observer) { int index = indexOf(observer); if (index != -1) { observers.remove(index); return true; } return false; }
python
def open_required(func): """Decorator to specify that the J-Link DLL must be opened, and a J-Link connection must be established. Args: func (function): function being decorated Returns: The wrapper function. """ @functools.wraps(func) def wr...
java
@SuppressWarnings("rawtypes") protected String[] parseSequenceParameter(Map params, String paramName) throws TemplateModelException { Object paramModel = params.get(paramName); if (paramModel == null) { return null; } if (!(paramModel instanceof SimpleSequence)) { ...
python
def dumps(obj, preserve=False): """Stringifies a dict as toml :param obj: the object to be dumped into toml :param preserve: optional flag to preserve the inline table in result """ f = StringIO() dump(obj, f, preserve) return f.getvalue()
python
async def expand(self, request: Request, layer: BaseLayer): """ Expand a layer into a list of layers including the pauses. """ if isinstance(layer, lyr.RawText): t = self.reading_time(layer.text) yield layer yield lyr.Sleep(t) elif isinstance...
python
def line_is_continuation(line: str) -> bool: """ Args: line Returns: True iff line is a continuation line, else False. """ llstr = line.lstrip() return len(llstr) > 0 and llstr[0] == "&"
java
public void marshall(Cluster cluster, ProtocolMarshaller protocolMarshaller) { if (cluster == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(cluster.getBackupPolicy(), BACKUPPOLICY_BINDING); ...
python
def unstack(self, unstacker_func, fill_value): """Return a blockmanager with all blocks unstacked. Parameters ---------- unstacker_func : callable A (partially-applied) ``pd.core.reshape._Unstacker`` class. fill_value : Any fill_value for newly introduced...
python
def _process_state(self): """Process the application state configuration. Google Alerts manages the account information and alert data through some custom state configuration. Not all values have been completely enumerated. """ self._log.debug("Capturing state from the r...
python
def duration_outside_nwh( self, starttime: datetime.time = datetime.time(NORMAL_DAY_START_H), endtime: datetime.time = datetime.time(NORMAL_DAY_END_H), weekdays_only: bool = False, weekends_only: bool = False) -> datetime.timedelta: """ Returns...
python
def ls_demux(sel, ls_di, lsls_do): """ Demultiplexes an input signal structure to list of output structures. A structure is represented by a list of signals: [signal_1, signal_2, ..., signal_n] lsls_do[sel][0] = ls_di[0] lsls_do[sel][1] = ls_di[1] ... lsls_do...
java
public static String decode(String encoded) { String raw = encoded.replace("%2F", "/"); raw = raw.replace("%2A", "%"); return raw; }
java
public final void elementValuePair() throws RecognitionException { int elementValuePair_StartIndex = input.index(); try { if ( state.backtracking>0 && alreadyParsedRule(input, 68) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:625:5: ( ( Identifier '=' )? elementValue )...
python
def _extract_split_and_discordants(in_bam, work_dir, data): """Retrieve split-read alignments from input BAM file. """ sr_file = os.path.join(work_dir, "%s-sr.bam" % os.path.splitext(os.path.basename(in_bam))[0]) disc_file = os.path.join(work_dir, "%s-disc.bam" % os.path.splitext(os.path.basename(in_bam...
python
def has_active_condition(self, condition, instances): """ Given a list of instances, and the condition active for this switch, returns a boolean representing if the conditional is met, including a non-instance default. """ return_value = None for instance in insta...
python
def p_default_option(self, p): """default_option : EQ primitive | EQ tag_ref | empty""" if p[1]: if isinstance(p[2], AstTagRef): p[0] = p[2] else: p[0] = p[2]
java
public void marshall(ThingGroupIndexingConfiguration thingGroupIndexingConfiguration, ProtocolMarshaller protocolMarshaller) { if (thingGroupIndexingConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarsha...
python
def _get_web_auth_token(self): """ Retrieves a token from the network for web authentication. The token then has to be authorized from getAuthURL before creating session. """ request = _Request(self.network, "auth.getToken") # default action is that a request is...
python
def output_domain(gandi, domain, output_keys, justify=12): """ Helper to output a domain information.""" if 'nameservers' in domain: domain['nameservers'] = format_list(domain['nameservers']) if 'services' in domain: domain['services'] = format_list(domain['services']) if 'tags' in dom...
java
public static AssertionError expectFailure(StandardSubjectBuilderCallback assertionCallback) { ExpectFailure expectFailure = new ExpectFailure(); expectFailure.enterRuleContext(); // safe since this instance doesn't leave this method assertionCallback.invokeAssertion(expectFailure.whenTesting()); return...
java
public static String escape(String str) { int i, max; StringBuilder result; char c; max = str.length(); for (i = 0; i < max; i++) { if (str.charAt(i) < 32) { break; } } if (i == max) { return str; } ...
python
def eeg_psd(raw, sensors_include="all", sensors_exclude=None, fmin=0.016, fmax=60, method="multitaper", proj=False): """ Compute Power-Spectral Density (PSD). Parameters ---------- raw : mne.io.Raw Raw EEG data. sensors_include : str Sensor area to include. See :func:`neurokit.e...
python
def refresh(self, using=None, **kwargs): """ Preforms a refresh operation on the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.refresh`` unchanged. """ return self._get_connection(using).indices.refresh(index=self._name, **kwargs)
python
def _add_dep(self, dep): """ Increment the reference count for *dep*. If this is a new dependency, then connect to its *changed* event. """ if dep in self._deps: self._deps[dep] += 1 else: self._deps[dep] = 1 dep._dependents[self] = None
java
void localGoto(String name, float llx, float lly, float urx, float ury) { PdfAction action = getLocalGotoAction(name); annotationsImp.addPlainAnnotation(new PdfAnnotation(writer, llx, lly, urx, ury, action)); }
python
def from_path(path): """ Selects and returns a build class based on project structure/config from a given path. :param path(str): required path argument to be used """ for item in ref: build = ref[item] valid_ = build['is_valid'] if valid_(path) is True: return build['builder'](path) rais...
python
def pca(df, n_components=2, mean_center=False, fcol=None, ecol=None, marker='o', markersize=40, threshold=None, label_threshold=None, label_weights=None, label_scores=None, return_df=False, show_covariance_ellipse=False, *args, **kwargs): """ Perform Principal Component Analysis (PCA) from input DataFrame and g...
java
@Override public void handleRequest(final Request request) { if (!isDisabled()) { final SelectToggleModel model = getComponentModel(); String requestParam = request.getParameter(getId()); final State newValue; if ("all".equals(requestParam)) { newValue = State.ALL; } else if ("none".equals(reques...
python
def findAllExceptions(pathToCheck): """ Find patterns of exceptions in a file or folder. @param patternFinder: a visitor for pattern checking and save results @return: patterns of special functions and classes """ finder = PatternFinder() if os.path.isfile(pathToCheck): with open(pa...
python
def range_intersect(a, b, extend=0): """ Returns the intersection between two reanges. >>> range_intersect((30, 45), (55, 65)) >>> range_intersect((48, 65), (45, 55)) [48, 55] """ a_min, a_max = a if a_min > a_max: a_min, a_max = a_max, a_min b_min, b_max = b if b_min > ...
java
public static XContentBuilder marshall(GatewayBean bean) throws StorageException { try (XContentBuilder builder = XContentFactory.jsonBuilder()) { preMarshall(bean); builder .startObject() .field("id", bean.getId()) .field("name", b...
java
public void offlineRegion(String resourceGroupName, String accountName, String region) { offlineRegionWithServiceResponseAsync(resourceGroupName, accountName, region).toBlocking().last().body(); }
java
public static WxOutMsg respVideo(String to, String mediaId, String title, String description) { WxOutMsg out = new WxOutMsg("video"); out.setVideo(new WxVideo(mediaId, title, description)); if (to != null) out.setToUserName(to); return out; }
python
def printTPRegionParams(tpregion): """ Note: assumes we are using TemporalMemory/TPShim in the TPRegion """ tm = tpregion.getSelf()._tfdr print "------------PY TemporalMemory Parameters ------------------" print "numberOfCols =", tm.columnDimensions print "cellsPerColumn =", tm.cell...
java
public static double nextDouble(Random random, final double min, final double max) { Validate.isTrue(max >= min, "Start value must be smaller or equal to end value."); MoreValidate.nonNegative("min", min); if (Double.compare(min, max) == 0) { return min; } return min + ((max - min) * random.nextDouble())...
java
public static nssimpleacl6_stats get(nitro_service service) throws Exception{ nssimpleacl6_stats obj = new nssimpleacl6_stats(); nssimpleacl6_stats[] response = (nssimpleacl6_stats[])obj.stat_resources(service); return response[0]; }
java
public OpenIdUserInfo getInfo(String authorization) throws ApiException { ApiResponse<OpenIdUserInfo> resp = getInfoWithHttpInfo(authorization); return resp.getData(); }
python
def _set_learning_mode(self, v, load=False): """ Setter method for learning_mode, mapped from YANG variable /mac_address_table/learning_mode (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_learning_mode is considered as a private method. Backends lookin...
python
def cholesky(A, ordering_method='default', return_type=RETURN_P_L, use_long=False): ''' P A P' = L L' ''' logger.debug('Calculating cholesky decomposition for matrix {!r} with ordering method {}, return type {} and use_long {}.'.format(A, ordering_method, return_type, use_long)) ## check input ...
python
def gen_submodule_names(package): """Walk package and yield names of all submodules :type package: package :param package: The package to get submodule names of :returns: Iterator that yields names of all submodules of ``package`` :rtype: Iterator that yields ``str`` """ for importer, modn...
java
public void writeValue(@NotNull Object entity, @Nullable Object value) { try { getWriteMethod().invoke(entity, value); } catch (InvocationTargetException | IllegalAccessException e) { LOGGER.warn("Can't invoker write method", e); } }
python
def fieldnames(self, keyword=''): """Get the names of the fields in a table keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub...
java
public ServiceFuture<WorkerPoolResourceInner> getWorkerPoolAsync(String resourceGroupName, String name, String workerPoolName, final ServiceCallback<WorkerPoolResourceInner> serviceCallback) { return ServiceFuture.fromResponse(getWorkerPoolWithServiceResponseAsync(resourceGroupName, name, workerPoolName), servi...
java
public void setAttribute(String name, String value, String facet) throws JspException { // validate the name attribute, in the case of an error simply return. if (name == null || name.length() <= 0) { String s = Bundle.getString("Tags_AttributeNameNotSet"); regist...
python
def dbmax_stddev(self, value=None): """ Corresponds to IDD Field `dbmax_stddev` Standard deviation of extreme annual maximum dry-bulb temperature Args: value (float): value for IDD Field `dbmax_stddev` Unit: C if `value` is None it will not be checke...
java
private CellRendererPane createCustomCellRendererPane() { return new CellRendererPane() { @Override public void paintComponent(Graphics graphics, Component component, Container container, int x, int y, int w, int h, boolean shouldValidate) { int ro...
python
def _scan_pth_files(dir_paths): """Given an iterable of directory paths, yield paths to all .pth files within.""" for dir_path in dir_paths: if not os.path.exists(dir_path): continue pth_filenames = (f for f in os.listdir(dir_path) if f.endswith('.pth')) for pth_filename in pth_filena...
python
def upload_path(instance, filename): ''' This method is created to return the path to upload files. This path must be different from any other to avoid problems. ''' path_separator = "/" date_separator = "-" ext_separator = "." empty_string = "" # get the model name model_name = ...
java
protected int getNumOfCols() { if (!columns.isEmpty()) return getHeadRegularColCnt() + columns.size(); if (loaded && !colTitleWidgets.isEmpty()) return getHeadRegularColCnt() + colTitleWidgets.size(); return getHeadRegularColCnt(); }
python
def bend_miter_Miller(Di, angle, Re, roughness=0.0, L_unimpeded=None): r'''Calculates the loss coefficient for a single miter bend according to Miller [1]_. This is a sophisticated model which uses corrections for pipe roughness, the length of the pipe downstream before another interruption, and a cor...
python
def host_report_msg(hostname, module_name, result, oneline): ''' summarize the JSON results for a particular host ''' failed = utils.is_failed(result) msg = '' if module_name in [ 'command', 'shell', 'raw' ] and 'ansible_job_id' not in result and result.get('parsed',True) != False: if not faile...
python
def hotstart(self): """ Prepare simulation hotstart info """ if self.write_hotstart: hotstart_time_str = self.event_manager.simulation_end.strftime("%Y%m%d_%H%M") try: os.mkdir('hotstart') except OSError: pass ...
java
public void setSubObj(Integer newSubObj) { Integer oldSubObj = subObj; subObj = newSubObj; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.OBJECT_COUNT__SUB_OBJ, oldSubObj, subObj)); }
python
def get_interactive_console(thread_id, frame_id, frame, console_message): """returns the global interactive console. interactive console should have been initialized by this time :rtype: DebugConsole """ if InteractiveConsoleCache.thread_id == thread_id and InteractiveConsoleCache.frame_id == frame_...
python
def fit(self, X): """Compute the Robust Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, timepoints] Each element in the list contains the fMRI data of one subject. """ logger.info('Starting RSRM') # ...
python
def _run_init_queries(self): ''' Initialization queries ''' for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir): self._db.create_table_from_object(obj())
java
public static void openEmbeddedDialog( final CmsEmbeddedDialogContext dialogContext, Map<String, String[]> params, boolean includeWebOus) { String[] param = params.get(PARAM_OU); String ou; if ((param != null) && (param.length >= 1)) { ou = param[0]; ...
java
public ServiceFuture<List<FaceList>> listAsync(final ServiceCallback<List<FaceList>> serviceCallback) { return ServiceFuture.fromResponse(listWithServiceResponseAsync(), serviceCallback); }
python
def marvcli_comment_list(datasets): """Lists comments for datasets. Output: setid comment_id date time author message """ app = create_app() ids = parse_setids(datasets, dbids=True) comments = db.session.query(Comment)\ .options(db.joinedload(Comment.dataset))\ ...
python
def get_document_list(self): """ Retrieves all documents included in this project. """ try: return self.__dict__['document_list'] except KeyError: obj_list = DocumentSet([ self._connection.documents.get(i) for i in self.document_ids ...
python
def kallisto_general_stats_table(self): """ Take the parsed stats from the Kallisto report and add it to the basic stats table at the top of the report """ headers = OrderedDict() headers['fragment_length'] = { 'title': 'Frag Length', 'description': 'Estimated av...
java
private boolean authenticate(byte method, InputStream in, BufferedOutputStream out) throws IOException { return authenticate(method, in, out, 0L); }
python
def repr_part(self): """Return a string usable in a space's ``__repr__`` method.""" optargs = [('norm', self.norm, ''), ('exponent', self.exponent, 2.0)] return signature_string([], optargs, mod=[[], ['!r', ':.4']])
python
def _LinearMapByteStream( self, byte_stream, byte_offset=0, context=None, **unused_kwargs): """Maps a data type sequence on a byte stream. Args: byte_stream (bytes): byte stream. byte_offset (Optional[int]): offset into the byte stream where to start. context (Optional[DataTypeMapContex...
python
def delete_dcnm_out_nwk(self, tenant_id, fw_dict, is_fw_virt=False): """Delete the DCNM OUT network and update the result. """ tenant_name = fw_dict.get('tenant_name') ret = self._delete_service_nwk(tenant_id, tenant_name, 'out') if ret: res = fw_const.DCNM_OUT_NETWORK_DEL_SU...
java
public SVGPath relativeQuadTo(double c1x, double c1y, double x, double y) { return append(PATH_QUAD_TO_RELATIVE).append(c1x).append(c1y).append(x).append(y); }
java
public static void isTrue(Boolean condition, Supplier<String> message) { if (isNotTrue(condition)) { throw new IllegalArgumentException(message.get()); } }
java
private String getBshPrompt() { if ( null != prompt ) return prompt; try { prompt = (String) eval("getBshPrompt()"); } catch ( Exception e ) { prompt = "bsh % "; } return prompt; }
java
@Override public DescribeSeverityLevelsResult describeSeverityLevels(DescribeSeverityLevelsRequest request) { request = beforeClientExecution(request); return executeDescribeSeverityLevels(request); }
python
def from_composition_and_entries(comp, entries_in_chemsys, working_ion_symbol="Li"): """ Convenience constructor to make a ConversionElectrode from a composition and all entries in a chemical system. Args: comp: Starting composition for C...
java
public DatabaseConnectionRequest<T, U> setConnection(String connection) { request.addParameter(ParameterBuilder.CONNECTION_KEY, connection); return this; }
java
public ClassificationModel attachLink(ClassificationModel classificationModel, LinkModel linkModel) { for (LinkModel existing : classificationModel.getLinks()) { if (StringUtils.equals(existing.getLink(), linkModel.getLink())) { return classificationModel; ...
java
public synchronized void registerPrimarySsId(String address, Long ssid) throws IOException { String node = getSsIdNode(address); zkCreateRecursively(node, SerializableUtils.toBytes(ssid), true, ssid.toString()); }
python
def _max_args(self, f): """ Returns maximum number of arguments accepted by given function. """ if f.func_defaults is None: return f.func_code.co_argcount return f.func_code.co_argcount + len(f.func_defaults)
java
@Override public RequestCtx handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (logger.isDebugEnabled()) { logger.debug("{}/handleRequest!", this.getClass().getName()); } ...
python
def update(self, id=None, new_data={}, **kwargs): """Update an object on the server. Args: id: ID of the object to update (can be None if not required) new_data: the update data for the object **kwargs: Extra options to send to the server (e.g. sudo) Returns...
java
public static <V> ExecutorCommand<V> executor(String circuitName) { CommandConfig commandConfig = new CommandConfig(); commandConfig.setCommandName(circuitName); return new ExecutorCommand<>(commandConfig); }
python
def get_parents(self, id_): """Gets the parents of the given ``id``. arg: id (osid.id.Id): the ``Id`` to query return: (osid.id.IdList) - the parents of the ``id`` raise: NotFound - ``id`` is not found raise: NullArgument - ``id`` is ``null`` raise: OperationFailed...
java
public static AssociativeArray sortAssociativeArrayByValueAscending(AssociativeArray associativeArray) { ArrayList<Map.Entry<Object, Object>> entries = new ArrayList<>(associativeArray.entrySet()); Collections.sort(entries, (Map.Entry<Object, Object> a, Map.Entry<Object, Object> b) -> { Doub...
python
def _scan_line(self, line): """ Reviews each line in email message and determines fragment type line - a row of text from an email message """ is_quote_header = self.QUOTE_HDR_REGEX.match(line) is not None is_quoted = self.QUOTED_REGEX.match(line) is not None is_head...
java
void commitTempFile(File temp) throws ConfigurationPersistenceException { if (!doneBootup.get()) { return; } if (!interactionPolicy.isReadOnly()) { FilePersistenceUtils.moveTempFileToMain(temp, mainFile); } else { FilePersistenceUtils.moveTempFileToMai...
python
def column(environment, book, sheet_name, sheet_source, column_source, column_key): """ Returns an array of values from column from a different dataset, ordered as the key. """ a = book.sheets[sheet_source] b = book.sheets[sheet_name] return environment.copy([a.get(**{column_key: row[column_key...
java
public static <T> Collector<T, List<T>> toList() { return new Collector<T, List<T>>() { @Override public List<T> collect(Stream<? extends T> stream) { return Lists.newArrayList(stream.iterator()); } }; }
java
public static Object getTopScopeValue(Scriptable scope, Object key) { scope = ScriptableObject.getTopLevelScope(scope); for (;;) { if (scope instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)scope; Object value = so.getAssociatedValue(...
java
public long getLong(String name, long defaultValue) { String valueString = getTrimmed(name); if (valueString == null) return defaultValue; String hexString = getHexDigits(valueString); if (hexString != null) { return Long.parseLong(hexString, 16); } return Long.parseLong(valueString); }
java
public int findRegion(int idx) { for (int i = 0; i < populationSize; i++) { if (subregionIdx[i][idx] == 1) { return i; } } return -1; }
java
public String getModality() { if (Event_Type.featOkTst && ((Event_Type)jcasType).casFeat_modality == null) jcasType.jcas.throwFeatMissing("modality", "de.unihd.dbs.uima.types.heideltime.Event"); return jcasType.ll_cas.ll_getStringValue(addr, ((Event_Type)jcasType).casFeatCode_modality);}
python
def resp_set_light(self, resp, color=None): """Default callback for set_color """ if color: self.color=color elif resp: self.power_level = resp.power_level self.color = resp.color self.label = resp.label.decode().replace("\x00", "")
java
public OkRequest<T> part(final String name, final String filename, final String contentType, final InputStream part) throws IOException { try { startPart(); writePartHeader(name, filename, contentType); copy(part, mOutput); } catch (IOExc...
python
def get_line_rules(declarations): """ Given a list of declarations, return a list of output.Rule objects. This function is wise to line-<foo>, inline-<foo>, and outline-<foo> properties, and will generate multiple LineSymbolizers if necessary. """ property_map = {'line-color': 'stro...
java
public List<I_CmsFormatterBean> getDisplayFormatters() { if (m_displayFormatters == null) { List<I_CmsFormatterBean> formatters = new ArrayList<I_CmsFormatterBean>( Collections2.filter(m_allFormatters, new IsDisplay())); if (formatters.size() > 1) { Colle...
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case BpsimPackage.PRIORITY_PARAMETERS__INTERRUPTIBLE: setInterruptible((Parameter)newValue); return; case BpsimPackage.PRIORITY_PARAMETERS__PRIORITY: setPriority((Parameter)newValue); return; } super.eSet(feat...
java
@SuppressWarnings("deprecation") public boolean isInheritedContainer(CmsObject cms) throws CmsException { if (m_resource == null) { initResource(cms); } return OpenCms.getResourceManager().getResourceType( CmsResourceTypeXmlContainerPage.INHERIT_CONTAINER_TYPE_NAME)....
java
public static void encodeDropMenuStart(DropMenu c, ResponseWriter rw, String l) throws IOException { rw.startElement("ul", c); if (c.getContentClass() != null) rw.writeAttribute("class", "dropdown-menu " + c.getContentClass(), "class"); else rw.writeAttribute("class", "dropdown-menu", "class"); if (null !...