language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private static String formatDate(Date date) { String dateStr = dateFormat.format(date); // insert colon into timezone return dateStr.substring(0, 22) + ":" + dateStr.substring(22); }
java
public static String getAppidFromAuthHeader(String authorization) { if (StringUtils.isBlank(authorization)) { return ""; } String appid = ""; // JWT token if (StringUtils.startsWith(authorization, "Bearer")) { try { String[] parts = StringUtils.split(authorization, '.'); if (parts.length > 1) { ...
java
public RevocationRequest setParameters(Map<String, String[]> parameters) { return setParameters(URLCoder.formUrlEncode(parameters)); }
java
public void unregister(final Object listener) { for (Class clazz = listener.getClass(); clazz != null; clazz = clazz.getSuperclass()) { this.handlersByEventType.removeAll(clazz); } }
python
def verify_create_instance(self, **kwargs): """Verifies an instance creation command. Without actually placing an order. See :func:`create_instance` for a list of available options. Example:: new_vsi = { 'domain': u'test01.labs.sftlyr.ws', '...
python
def _get_datatable_options(self): """ Helps to keep the promise that we only run ``get_datatable_options()`` once. """ if not hasattr(self, '_datatable_options'): self._datatable_options = self.get_datatable_options() # Convert sources from list to tuple, so that modern Column t...
python
def applyFunction(self, func): """ Applies a function to the dataFrame with appropriate signals. The function must return a dataframe. :param func: A function (or partial function) that accepts a dataframe as the first argument. :return: None :raise: Assertion...
python
def get_elapsed_time(self, issue): """ Gets the elapsed time since the last mark (either the updated time of the last log or the time that the issue was marked in progress) """ last_mark = None # Get the last mark from the work logs worklogs = self.get_worklog(is...
java
@Override public BinaryType getBinaryType() throws IllegalStateException { checkConnected(); return BinaryType.valueOf( _webSocket.getBinaryType().toUpperCase() ); }
java
public Datatype.Builder setExtensible(boolean extensible) { this.extensible = extensible; _unsetProperties.remove(Property.EXTENSIBLE); return (Datatype.Builder) this; }
python
def is_default(self): """ ``True`` if values of all config items in this section and its subsections have their values equal to defaults or have no value set. """ for _, item in self.iter_items(recursive=True): if not item.is_default: return False ...
python
def write_tsv(output_stream, *tup, **kwargs): """ Write argument list in `tup` out as a tab-separeated row to the stream. """ encoding = kwargs.get('encoding') or 'utf-8' value = '\t'.join([s for s in tup]) + '\n' output_stream.write(value.encode(encoding))
java
public void setConfigurationProperties(java.util.Collection<ActionConfigurationProperty> configurationProperties) { if (configurationProperties == null) { this.configurationProperties = null; return; } this.configurationProperties = new java.util.ArrayList<ActionConfigur...
python
def get_proficiencies_for_objective_on_date(self, objective_id, from_, to): """Gets a ``ProficiencyList`` relating to the given objective effective during the entire given date range inclusive but not confined to the date range. arg: objective_id (osid.id.Id): an objective ``Id`` arg: fro...
java
public TaglibType<JspConfigType<T>> getOrCreateTaglib() { List<Node> nodeList = childNode.get("taglib"); if (nodeList != null && nodeList.size() > 0) { return new TaglibTypeImpl<JspConfigType<T>>(this, "taglib", childNode, nodeList.get(0)); } return createTaglib(); }
java
private final void init() { InputStream in = null; try { URL url = this.getClass() .getClassLoader() .getResource("padawan.conf.xml"); if (url != null) { URLConnection conn = url.openConnection(); ...
java
@Override public GoogleCloudStorageItemInfo getItemInfo(StorageResourceId resourceId) throws IOException { logger.atFine().log("getItemInfo(%s)", resourceId); // Handle ROOT case first. if (resourceId.isRoot()) { return GoogleCloudStorageItemInfo.ROOT_INFO; } GoogleCloudStorageItemIn...
python
def merge(var1, var2): """ Take two copies of a variable and reconcile them. var1 is assumed to be the higher-level variable, and so will be overridden by var2 where such becomes necessary. """ out = {} out['value'] = var2.get('value', var1.get('value', None)) out['mimetype'] = var2.get(...
java
public String getReadable( Node node ) { if (node == null) return ""; try { return node.getPath(); } catch (RepositoryException err) { return node.toString(); } }
python
def _MStep(self, l, K, x, z_h1, pi_h1, p_h1, p_h, delta_i_j_s): """ Description: Internal function for computing the M-Step of the EMM algorithm, which is itself an MM algorithm. """ for k in range(K): normconst = 0 if l == 0: # only need t...
python
def update_vertices(self, mask): """ Apply a mask to remove or duplicate vertex properties. """ if self.uv is not None: self.uv = self.uv[mask]
python
def url(self): """ Returns url for accessing stage instance. """ return "{server_url}/go/pipelines/{pipeline_name}/{pipeline_counter}/{stage_name}/{stage_counter}".format( server_url=self._session.server_url, pipeline_name=self.pipeline_name, pipeline_...
python
def to_google_str(self): """ Convert to Google's bounds format: 'latMin,lonMin|latMax,lonMax' """ vb = self.convert_srs(4326) return '%s,%s|%s,%s' % (vb.bottom, vb.left, vb.top, vb.right)
python
def setup(config_root=''): """ Service configuration and logging setup. Configuration defined in ``gordon-janitor-user.toml`` will overwrite ``gordon-janitor.toml``. Args: config_root (str): where configuration should load from, defaults to current working directory. Return...
java
public static final Function<BigDecimal,BigDecimal> roundBigDecimal(final int scale, final RoundingMode roundingMode) { return FnNumber.roundBigDecimal(scale, roundingMode); }
java
public void publish(final List<StepImplementationsDescriptor> stepimplementationDescriptors) { final Map<String, List<StepDescriptor>> sectionSorted = new TreeMap<String, List<StepDescriptor>>(); for (final StepImplementationsDescriptor descriptor : stepimplementationDescriptors) { for (fi...
java
public static final Function<Number,Double> toDouble(final int scale, final RoundingMode roundingMode) { return new ToDouble(scale, roundingMode); }
java
public static <T> RiakUserMetadata getUsermetaData(RiakUserMetadata metaContainer, T domainObject) { return AnnotationHelper.getInstance().getUsermetaData(metaContainer, domainObject); }
python
def reload_all_plugins(self, *args): """ Reloads all initialized plugins """ for manifest in self._manifests[:]: if self.get_plugin(manifest["name"]) is not None: self.reload_plugin(manifest["name"], *args)
python
def findall(data): """ Worker that finds all occurrences of a given string (or regex) in a given text. :param data: Request data dict:: { 'string': string to search in text 'sub': input text 'regex': True to consider string as a regular expression ...
java
protected void onUnload() { if (registrations != null) { for (HandlerRegistration registration : registrations) { registration.removeHandler(); } } loadedRegistration.removeHandler(); super.onUnload(); }
java
@Override public void metadataResolved(RepositoryEvent event) { log.fine("Resolved metadata " + event.getMetadata() + " from " + event.getRepository()); }
python
def _login(self): """ Login with your Google account :return: """ # TODO(dmvieira) login changed to oauth2 self.gc = self.gspread.login(self.email, self.password)
python
def _exists(field, value, document): """ Ensures a document has a given field or not. ``value`` must be either True or False, otherwise a MalformedQueryException is raised """ if value not in (True, False): raise MalformedQueryException("'$exists' must be supplied a boolean") if value: ...
java
public boolean isAnimate() { Boolean value = (Boolean) getStateHelper().eval(PropertyKeys.animate, false); return (boolean) value; }
java
public int partition(int k, int minPts) { List<Neuron> data = new ArrayList<>(); for (Neuron neuron : neurons) { neuron.y = OUTLIER; if (neuron.n >= minPts) { data.add(neuron); } } double[][] proximity = new double[data.size()]...
python
def json(self): """ Return a JSON-serializable representation of this result. The output of this function can be converted to a serialized string with :any:`json.dumps`. """ data = { "segment_name": self.segment_name, "formula": self.formula, ...
python
def _drawPoints(self, pen, **kwargs): """ Subclasses may override this method. """ # The try: ... except TypeError: ... # handles backwards compatibility with # point pens that have not been upgraded # to point pen protocol 2. try: pen.beginPat...
python
def _set_overlay_verify(name, overlay_path, config_path): """ _set_overlay_verify - Function to load the overlay and verify it was setup properly """ global DEBUG # VERIFY PATH IS NOT THERE if os.path.exists(config_path): print("Config path already exists! Not moving forward") p...
java
public static HtmlTree HEADER() { HtmlTree htmltree = new HtmlTree(HtmlTag.HEADER); htmltree.setRole(Role.BANNER); return htmltree; }
java
@Deprecated public void copyFromMaster(Storable indexEntry, S master) throws FetchException { getReferenceAccess().copyFromMaster(indexEntry, master); }
java
@Override public void started(ServiceBroker broker) throws Exception { super.started(broker); // Set components ServiceBrokerConfig cfg = broker.getConfig(); serviceRegistry = cfg.getServiceRegistry(); contextFactory = cfg.getContextFactory(); // Start timer if (cleanup > 0) { timer = b...
java
public static int clamp(int n, int min, int max) { if (n < min) return min; if (n > max) return max; return n; }
java
public boolean addEvent(ISharedObjectEvent.Type type, String key, Object value) { return events.add(new SharedObjectEvent(type, key, value)); }
java
public DeclaredType findSupertype(TypeMirror type, String qualifiedName) { TypeElement element = asTypeElement(type); if (element != null && element.getQualifiedName().toString().equals(qualifiedName)) { return (DeclaredType) type; } for (TypeMirror t : directSupertypes(type)) { DeclaredType...
java
public static String deepCleanSequence(String sequence) { sequence = SequenceUtil.cleanSequence(sequence); sequence = SequenceUtil.DIGIT.matcher(sequence).replaceAll(""); sequence = SequenceUtil.NONWORD.matcher(sequence).replaceAll(""); final Pattern othernonSeqChars = Pattern.compile("[_-]+"); sequence = othernon...
python
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents :returns: Updated XML element :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) ...
java
private static List<List<String>> doParse(String appliesTo) { boolean quoted = false; int index = 0; List<String> entry = new ArrayList<String>(); List<List<String>> result = new ArrayList<List<String>>(); for (int i = 0; i < appliesTo.length(); i++) { char c = appli...
python
def adafactor_decay_rate_adam(beta2): """Second-moment decay rate like Adam, subsuming the correction factor. Args: beta2: a float between 0 and 1 Returns: a scalar """ t = tf.cast(tf.train.get_or_create_global_step(), tf.float32) + 1.0 decay = beta2 * (1.0 - tf.pow(beta2, t - 1.0)) / (1.0 - tf.pow...
java
public void initFromSetupBean(String webapp) { String db = m_setupBean.getDatabase(); CmsSetupBean bean = m_setupBean; Map<String, String[]> params = new HashMap<>(); m_setupPanel.setVisible(true); switch (db) { case "mysql": case "mssql": ...
java
public com.liferay.commerce.product.type.grouped.service.CPDefinitionGroupedEntryLocalService getCPDefinitionGroupedEntryLocalService() { return cpDefinitionGroupedEntryLocalService; }
python
def render_q(q, qn, connection): """ Renders the Q object into SQL for the WHEN clause. Uses as much as possible the Django ORM machinery for SQL generation, handling table aliases, field quoting, parameter escaping etc. :param q: Q object representing the filter condition :param qn: db specif...
java
public static String getName(String path, boolean ignoreTrailingSlash) { if (ignoreTrailingSlash && path.endsWith("/") && path.length() > 1) { path = path.substring(0, path.length() - 1); } return getName(path); }
python
def stop(self, stopSparkContext=True, stopGraceFully=False): """ Stop the execution of the streams, with option of ensuring all received data has been processed. @param stopSparkContext: Stop the associated SparkContext or not @param stopGracefully: Stop gracefully by waiting fo...
java
public List<PostOfficeElement.PostOfficeName> getPostOfficeName() { if (postOfficeName == null) { postOfficeName = new ArrayList<PostOfficeElement.PostOfficeName>(); } return this.postOfficeName; }
java
public void addApiOptions(AbstractParam param) { // Add option parameter getters and setters via reflection this.param = param; Method[] methods = param.getClass().getDeclaredMethods(); Arrays.sort(methods, METHOD_NAME_COMPARATOR); List<String> addedActions = new ArrayList<>(); // Check for string setters (...
java
static void configJFinal(JFinalConfig jfinalConfig) { jfinalConfig.configConstant(constants); initLogFactory(); initEngine(); configPluginWithOrder(1, jfinalConfig); jfinalConfig.configRoute(routes); configPluginWithOrder(2, jfinalConfig); jfinalConfig.configEngine(engine); configPluginW...
python
def robust_zscore(mat, ctrl_mat=None, min_mad=0.1): ''' Robustly z-score a pandas df along the rows. Args: mat (pandas df): Matrix of data that z-scoring will be applied to ctrl_mat (pandas df): Optional matrix from which to compute medians and MADs (e.g. vehicle control) min_mad (float): M...
python
def register_plugin(self): """Register plugin in Spyder's main window""" self.breakpoints.edit_goto.connect(self.main.editor.load) #self.redirect_stdio.connect(self.main.redirect_internalshell_stdio) self.breakpoints.clear_all_breakpoints.connect( ...
java
@Nullable public Language getLanguage() { XComponent xComponent = OfficeTools.getCurrentComponent(xContext); Locale charLocale; XPropertySet xCursorProps; try { XModel model = UnoRuntime.queryInterface(XModel.class, xComponent); if(model == null) { return Languages.getLanguageForSh...
python
def ListComp(xp, fp, it, test=None): """A list comprehension of the form [xp for fp in it if test]. If test is None, the "if test" part is omitted. """ xp.prefix = u"" fp.prefix = u" " it.prefix = u" " for_leaf = Leaf(token.NAME, u"for") for_leaf.prefix = u" " in_leaf = Leaf(token.N...
python
def setBreakpoints( self, breakpoints ): """ Sets the breakpoints for this edit to the inputed list of breakpoints. :param breakpoints | [<int>, ..] """ self.clearBreakpoints() for breakpoint in breakpoints: self.addBreakpoint(breakpoint)
java
protected List<CmsContainerElement> getElements() { List<CmsContainerElement> subItems = new ArrayList<CmsContainerElement>(); Iterator<Widget> it = m_groupContainer.iterator(); while (it.hasNext()) { Widget w = it.next(); if (w instanceof CmsContainerPageElementPanel) {...
python
def Debugger_setAsyncCallStackDepth(self, maxDepth): """ Function path: Debugger.setAsyncCallStackDepth Domain: Debugger Method name: setAsyncCallStackDepth Parameters: Required arguments: 'maxDepth' (type: integer) -> Maximum depth of async call stacks. Setting to <code>0</code> will effective...
java
private static String discardBeginningHyphen(String string) { String noHyphenString = string; if (string.startsWith("-")) { noHyphenString = string.substring(1); // Oh well, just throw away // the awful "-". No one // will ever notice... } return noHyphenString; }
python
def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): """Issues a request to the jobs/getQueryResults method. Args: job_id: the id of job from a previously executed query. project_id: the project id to use to fetch the results; use None for the default project. ...
java
public static boolean allCoplanar(Vector3d planeNormal, Point3d pointInPlane, Point3d... points) { for (Point3d point : points) { double distance = StereoTool.signedDistanceToPlane(planeNormal, pointInPlane, point); if (distance < PLANE_TOLERANCE) { continue; ...
java
public Callable<?> handle(Object instance, Method origin, Object[] arguments) throws Throwable { try { return (Callable<?>) mAdvice.getClass().getMethod("handle", Object.class, Method.class, Object[].class).invoke(mAdvice, instance, origin, arguments); } catch (Invocation...
java
public static String getRevisionIdSuffix(String revId) { validateRevisionId(revId); int dashPos = revId.indexOf("-"); if (dashPos >= 0) { return revId.substring(dashPos + 1); } else { throw new IllegalStateException("The revId id should be valid: " + revId); ...
java
public void setMaxValue(final double MAX_VALUE) { // check min-max values if (Double.compare(MAX_VALUE, minValue) == 0) { throw new IllegalArgumentException("Max value cannot be equal to min value"); } if (Double.compare(MAX_VALUE, minValue) < 0) { maxValue = min...
java
public static File writeString(String content, File file, String charset) throws IORuntimeException { return FileWriter.create(file, CharsetUtil.charset(charset)).write(content); }
python
def onSendCommand(self): '''Called when user presses the 'send' button or presses 'Enter' while the command entry box has focus.''' self.agent_host.sendCommand(self.command_entry.get()) self.command_entry.delete(0,END) self.canvas.focus_set()
java
public static ByteArrayHolder zlibUncompressBuffer(byte[] bytes, int length, Integer uncompressedLen) throws IOException, DataFormatException, FileParsingException { Inflater inflater = new Inflater(); inflater.setInput(bytes, 0, length); int bufSize = uncompressedLen == null ? length * 2 : unc...
java
public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { updateCharacterStream(findColumn(columnLabel), reader, Long.MAX_VALUE); }
java
protected void shiftDown(int shift) { int max = getMaximumVerticalScrollPosition(); if ((m_currentValue + shift) < max) { setVerticalScrollPosition(m_currentValue + shift); } else { setVerticalScrollPosition(max); } }
java
public Reference addEpisodeOfCare() { //3 Reference t = new Reference(); if (this.episodeOfCare == null) this.episodeOfCare = new ArrayList<Reference>(); this.episodeOfCare.add(t); return t; }
python
def register(self, event_type, callback, args=None, kwargs=None, details_filter=None, weak=False): """Register a callback to be called when event of a given type occurs. Callback will be called with provided ``args`` and ``kwargs`` and when event type occurs (o...
java
public synchronized Record clear(final URI... properties) { final List<URI> propertiesToClear; if (properties == null || properties.length == 0) { propertiesToClear = doGetProperties(); } else { propertiesToClear = Arrays.asList(properties); } for (final U...
python
async def wait_for_action(self, action_id): """Given an action, wait for it to complete.""" if action_id.startswith("action-"): # if we've been passed action.tag, transform it into the # id that the api deltas will use. action_id = action_id[7:] def predicat...
java
public void add(T element) { if (this.locked) { this.toAdd.add(element); } else { this.list.add(element); } }
java
public double [][]EBEsMatrizMultiplicar(double [][]s, double[][]t) throws JMetalException{ int f, c, q; double [][]r = new double [s.length][t[0].length]; for(f=0; f<s.length; f++){ // cantidad de elementos de la 1ra dimensión for(c=0; c<s[f].length; c++){ //cantidad de elementos de la 2ra dimens...
python
def derive_and_set_slug(self, set_name_sort=True, set_slug=True): """ Derive `slug` field from `title` unless it is set in its own right. This method is called during `save()` """ # `title` is the primary required name field. It must be set. if is_empty(self.title): ...
java
@SuppressWarnings("unchecked") public final B addMapper(FieldMapper<ROW, T> mapper) { setRowMapperBuilder.addMapper(mapper); return (B) this; }
python
def signedMDS(cdm, W=None): """ Find the set of points from a cdm. """ N = cdm.shape[0] D_sym = (cdm - cdm.T) D_sym /= 2 if W is None: x_est = np.mean(D_sym, axis=1) x_est -= np.min(x_est) return x_est W_sub = W[1:, 1:] sum_W = np.sum(W[1:, :], axis=1) # ...
python
def load_stdlib(): '''Scans sys.path for standard library modules. ''' if _stdlib: return _stdlib prefixes = tuple({os.path.abspath(p) for p in ( sys.prefix, getattr(sys, 'real_prefix', sys.prefix), getattr(sys, 'base_prefix', sys.prefix), )}) for sp in sys.path...
python
async def _execute(self, fn, *args, **kwargs): """Queue a function with the given arguments for execution.""" function = partial(fn, *args, **kwargs) future = self._loop.create_future() self._tx.put_nowait((future, function)) return await future
python
def access_key_id(ecs_access_key_id): """Display / set / update the ECS access key id.""" if not ecs_access_key_id: click.secho(dtool_config.utils.get_ecs_access_key_id(CONFIG_PATH)) else: click.secho(dtool_config.utils.set_ecs_access_key_id( CONFIG_PATH, ecs_access_k...
python
def fold_text_stream(self, prefix, postfix="", hidden_stream=None, **kwargs): """ :param str prefix: always visible :param str postfix: always visible, right after. :param io.TextIOBase|io.StringIO hidden_stream: sys.stdout by default. If this is sys.stdout, it will replace t...
python
def validation_schema(name): """Return json schema for json validation.""" schemas = { 'processor': 'processSchema.json', 'descriptor': 'descriptorSchema.json', 'field': 'fieldSchema.json', 'type': 'typeSchema.json', } if name not in schemas: raise ValueError() ...
python
def _create_destination(self, server_id, dest_url, owned): """ Create a listener destination instance in the Interop namespace of a WBEM server and return that instance. In order to catch any changes the server applies, the instance is retrieved again using the instance path ret...
python
def printAggregateJobStats(self, properties, childNumber): """Prints a job's ID, log file, remaining tries, and other properties.""" for job in self.jobsToReport: lf = lambda x: "%s:%s" % (x, str(x in properties)) print("\t".join(("JOB:%s" % job, "LOG...
python
def getAllClasses(self, hide_base_schemas=True, hide_implicit_types=True): """ * hide_base_schemas: by default, obscure all RDF/RDFS/OWL/XML stuff * hide_implicit_types: don't make any inference based on rdf:type declarations """ query = """SELECT DISTINCT ?x ?c ...
python
def manifest_is_media_type(response, media_type): """ Attempt to confirm the returned manifest is of a given media type :param response: a requests.Response :param media_type: media_type (str), or None to confirm the media type cannot be guessed """ try: received_media_type = re...
python
def html_to_obj(cls, file_path=None, text='', columns=None, key_on=None, ignore_code_blocks=True, eval_cells=True): """ This will convert a html file or text to a seaborn table :param file_path: str of the path to the file :param text: str of the csv text :par...
java
public boolean isIgnored() { NodeMonitor m = ComputerSet.getMonitors().get(this); return m==null || m.isIgnored(); }
java
public static RubyRange<LocalDateTime> range(LocalDateTime start, LocalDateTime end) { return new RubyRange<>(LocalDateTimeSuccessor.getInstance(), start, end, Interval.CLOSED); }
java
public void setRegisterBlueprints(Collection blueprints) throws RegisterBlueprintException { for (Object blueprint : blueprints) { if (blueprint instanceof Class) { registerBlueprint((Class) blueprint); } else if (blueprint instanceof String) { registerBlu...
java
public CmsGroup readGroupOfProject(CmsUUID project) throws Exception { return m_cms.readGroup(m_cms.readProject(project)); }
python
def plot_parallel( data, var_names=None, coords=None, figsize=None, textsize=None, legend=True, colornd="k", colord="C1", shadend=0.025, ax=None, norm_method=None, ): """ Plot parallel coordinates plot showing posterior points with and without divergences. Descri...
python
def run_all(logdir, verbose=False): """Run simulations on a reasonable set of parameters. Arguments: logdir: the directory into which to store all the runs' data verbose: if true, print out each run's name as it begins """ run_box_to_gaussian(logdir, verbose=verbose) run_sobel(logdir, verbose=verbose...