language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static StringExpression left(Expression<String> lhs, int rhs) { return left(lhs, ConstantImpl.create(rhs)); }
python
def which(name, flags=os.X_OK): """Search PATH for executable files with the given name. ..note:: This function was taken verbatim from the twisted framework, licence available here: http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.2.0/LICENSE On newer versions of MS-Windows, the ...
java
private boolean prepareClusterState(ClusterServiceImpl clusterService, int expectedMemberListVersion) { if (!preCheckClusterState(clusterService)) { return false; } long until = Clock.currentTimeMillis() + mergeNextRunDelayMs; while (Clock.currentTimeMillis() < until) { ...
python
def cached(fun): """ memoizing decorator for linkage functions. Parameters have been hardcoded (no ``*args``, ``**kwargs`` magic), because, the way this is coded (interchangingly using sets and frozensets) is true for this specific case. For other cases that is not necessarily guaranteed. """ ...
python
def tb_capture(func): """A decorator which captures worker tracebacks. Tracebacks in particular, are captured. Inspired by an example in https://bugs.python.org/issue13831. This decorator wraps rio-mucho worker tasks. Parameters ---------- func : function A function to be decorate...
python
def deletion(args): """ %prog deletion [mac.mic.bam|mac.mic.bed] mic.gaps.bed Find IES based on mapping MAC reads to MIC genome. """ p = OptionParser(deletion.__doc__) p.add_option("--mindepth", default=3, type="int", help="Minimum depth to call a deletion") p.add_option("-...
java
public FavoriteResources favoriteResources() { if (favorites.get() == null) { favorites.compareAndSet(null, new FavoriteResourcesImpl(this)); } return favorites.get(); }
python
def search(path, pattern, flags=8, bufsize=1, ignore_if_missing=False, multiline=False ): ''' .. versionadded:: 0.17.0 Search for occurrences of a pattern in a file Except for multiline, params are identical to :py:func:`~salt.modules.file.replace`. ...
java
public boolean add(SimulatorEvent event) { if (lastEvent != null && event.getTimeStamp() < lastEvent.getTimeStamp()) throw new IllegalArgumentException("Event happens in the past: " + event.getClass()); event.setInternalCount(eventCount++); return events.add(event); }
java
public void marshall(UpdateServicePrimaryTaskSetRequest updateServicePrimaryTaskSetRequest, ProtocolMarshaller protocolMarshaller) { if (updateServicePrimaryTaskSetRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { proto...
java
private int getStatusBarHeight() { int result = 0; int resourceId = mHoldingActivity.getResources() .getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = mHoldingActivity.getResources().getDimensionPixelSize(resourceId); } ...
java
static String getCheckName( final String fieldName, final String checkName) { // I was going to try and generate "nice" private static final member // names from the field and check names but this would only work if the // user employed a set of naming conventions. ...
java
public void setDATAPOS(Integer newDATAPOS) { Integer oldDATAPOS = datapos; datapos = newDATAPOS; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.TILE_TOCRG__DATAPOS, oldDATAPOS, datapos)); }
java
public static void invokeSetter(Object object, String name, String value) throws NoSuchMethodException, Exception { String setterName = Strings.getMethodAccessor("set", name); Class<?> clazz = object.getClass(); Method method = findMethod(clazz, setterName); Class<?>[] parameterTypes = method.g...
java
@Override public void draw(@NonNull Canvas canvas) { if (mIcon == null && mPlainIcon == null) return; Rect viewBounds = getBounds(); updatePaddingBounds(viewBounds); updateTextSize(viewBounds); offsetIcon(viewBounds); if (mRoundedCornerRy > -1 && mRoundedCornerRx >...
java
private void handleTmpView(View v) { Address new_coord=v.getCoord(); if(new_coord != null && !new_coord.equals(coord) && local_addr != null && local_addr.equals(new_coord)) handleViewChange(v); }
java
public boolean containsTagHandler(String ns, String localName) { if (containsNamespace(ns)) { Map<String, TagHandlerFactory> map = _factories.get(ns); if (map == null) { return false; } return map.containsKey(localName); ...
java
private void addExampleUsingArrayList() { add(new WHeading(HeadingLevel.H3, "WCheckBoxSelect created using an array list of options")); List<CarOption> options = new ArrayList<>(); options.add(new CarOption("1", "Ferrari", "F-360")); options.add(new CarOption("2", "Mercedez Benz", "amg")); options.add(new Car...
java
public static void copyToClipboard(String text) { final StringSelection stringSelection = new StringSelection(text); final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, stringSelection); }
java
public <T extends Enum<T>> T getEnum(String name, T defaultValue) { final String val = get(name); return null == val ? defaultValue : Enum.valueOf(defaultValue.getDeclaringClass(), val); }
python
def runtime(self): """Return ellapsed time and reset start. """ t = time.time() - self.start self.start = time.time() return t
java
private boolean iterateSingleGroup(ValueIterator.Element result, int limit) { synchronized(GROUP_OFFSETS_) { synchronized(GROUP_LENGTHS_) { int index = m_name_.getGroupLengths(m_groupIndex_, GROUP_OFFSETS_, GROUP_LENGTHS_); whil...
java
protected void purgeDeviceObject(Long threadId, Integer deviceId, Long objectId, AllocationPoint point, boolean copyback) { memoryHandler.purgeDeviceObject(threadId, deviceId, objectId, point, copyback); // since we can't allow java object without native memory, we explicitly specif...
python
def list(self, **params): """ Retrieve all orders Returns all orders available to the user according to the parameters provided :calls: ``get /orders`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style access, whic...
java
public static Number count(Iterator self, Object value) { long answer = 0; while (self.hasNext()) { if (DefaultTypeTransformation.compareEqual(self.next(), value)) { ++answer; } } // for b/c with Java return an int if we can if (answer <= I...
python
def check_if_cached(self, job_spec, step, workflow_workspace): """Check if job result is in cache.""" response, http_response = self._client.job_cache.check_if_cached( job_spec=json.dumps(job_spec), workflow_json=json.dumps(step), workflow_workspace=workflow_workspace...
java
public void setHsms(java.util.Collection<Hsm> hsms) { if (hsms == null) { this.hsms = null; return; } this.hsms = new java.util.ArrayList<Hsm>(hsms); }
python
def add_nodes(self, nodes, nesting=1): """ Adds edges indicating the call-tree for the procedures listed in the nodes. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(...
java
public static ObjectModelResolver get(String resolverId) { List<ObjectModelResolver> resolvers = getResolvers(); for (ObjectModelResolver resolver : resolvers) { if (resolver.accept(resolverId)) { return resolver; } } return null; }
python
def SetServerInformation(self, server, port): """Sets the server information. Args: server (str): hostname or IP address of the database server. port (int): port number of the database server. """ self._host = server self._port = port
java
private Ref xorOp() throws PageException { Ref ref = orOp(); while (cfml.forwardIfCurrent("xor")) { cfml.removeSpace(); ref = new Xor(ref, orOp(), limited); } return ref; }
java
public float[] t3(float[] z) throws JMetalException { float[] result = new float[z.length]; for (int i = 0; i < z.length; i++) { result[i] = (new Transformations()).bPoly(z[i], (float) 0.02); } return result; }
java
public double interpolate(double... x) { if (x.length != this.x[0].length) { throw new IllegalArgumentException(String.format("Invalid input vector size: %d, expected: %d", x.length, this.x[0].length)); } double sum = 0.0, sumw = 0.0; for (int i = 0; i < this.x.length; i++) ...
python
def all_hosts(self): """List of hosts, passives, and arbiters known to this server.""" return set(imap(common.clean_node, itertools.chain( self._doc.get('hosts', []), self._doc.get('passives', []), self._doc.get('arbiters', []))))
java
@Override public UploadLayerPartResult uploadLayerPart(UploadLayerPartRequest request) { request = beforeClientExecution(request); return executeUploadLayerPart(request); }
python
def log(fn=None, logger=logging.getLogger(), debug_level=logging.DEBUG): """ logs parameters and result - takes no arguments """ if fn is None: return partial(log, logger=logger, debug_level=debug_level) @wraps(fn) def func(*args, **kwargs): arg_string = "" for i in rang...
java
public void marshall(AdminUpdateUserAttributesRequest adminUpdateUserAttributesRequest, ProtocolMarshaller protocolMarshaller) { if (adminUpdateUserAttributesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMar...
python
def diff(self): """Calculate difference between fs and db.""" done = set(self.done) return [name for name in self.todo if name not in done]
java
@VisibleForTesting void reassignPartitions(List<KafkaTopicPartitionState<TopicPartition>> newPartitions) throws Exception { if (newPartitions.size() == 0) { return; } hasAssignedPartitions = true; boolean reassignmentStarted = false; // since the reassignment may introduce several Kafka blocking calls th...
python
def _getattr (self, fieldname, raw=False, index=None): """Returns the value of the given packet field name. If raw is True, the field value is only decoded. That is no enumeration substituions or DN to EU conversions are applied. """ self._assertField(fieldname) value =...
python
def paste_to_current_cell(self, tl_key, data, freq=None): """Pastes data into grid from top left cell tl_key Parameters ---------- ul_key: Tuple \key of top left cell of paste area data: iterable of iterables where inner iterable returns string \tThe outer itera...
python
def check_curly_quotes(text): u"""Use curly quotes, not straight quotes.""" err = "typography.symbols.curly_quotes" msg = u'Use curly quotes “”, not straight quotes "".' list = [ [u"“ or ”", ['"']], ] return preferred_forms_check( text, list, err, msg, ignore_case=False, max_er...
python
def __ms_npenalty_fcn(self, axis, mask, orig_shape): """ :param axis: direction of edge :param mask: 3d ndarray with ones where is fine resolution Neighboorhood penalty between small pixels should be smaller then in bigger tiles. This is the way how to set it. """ ...
java
private boolean processingAllowed(final String prefix, final String variable, final TemplateReplacementContext context) { return (PREFIX.equals(prefix) && !StringUtils.isEmpty(variable) && context instanceof MailTemplateReplacementContext); }
python
def validate_python_version(): """Validate python interpreter version. Only 3.3+ allowed.""" python_version = LooseVersion(platform.python_version()) minimal_version = LooseVersion('3.3.0') if python_version < minimal_version: print("Sorry, Python 3.3+ is required") sys.exit(1)
java
public AnnotationInfo getAnnotationInfo(final String annotationClassName) { for(AnnotationInfo item : annotationInfos) { if(item.getClassName().equals(annotationClassName)) { return item; } } return null; }
java
@Pure @Inline(value = "(long) (($1).doubleValue() * $2.MILLIS_IN_HOUR)", imported = {TimeExtensions.class}) public static long hours(Number hours) { return (long) (hours.doubleValue() * MILLIS_IN_HOUR); }
java
static String getAttributeName(final String fieldName, final Attribute annot) { String attributeName = null; if (annot.name().equals("")) { attributeName = fieldName; } else { attributeName = annot.name(); } return attributeName; }
java
public String getLocation(Class<?> clazz) { String filename = clazz.getName().replace('.', '/'); int pos = filename.lastIndexOf('/') + 1; return (pos > 0 ? filename.substring(0, pos) : ""); }
python
def get_noqa_suppressions(file_contents): """ Finds all pep8/flake8 suppression messages :param file_contents: A list of file lines :return: A pair - the first is whether to ignore the whole file, the second is a set of (0-indexed) line numbers to ignore. """ ignore_whol...
python
def prepare_replicant_order_object(manager, snapshot_schedule, location, tier, volume, volume_type): """Prepare the order object which is submitted to the placeOrder() method :param manager: The File or Block manager calling this function :param snapshot_schedule: The pri...
python
def _format_jid_instance(jid, job): ''' Return a properly formatted jid dict ''' ret = _format_job_instance(job) ret.update({'StartTime': salt.utils.jid.jid_to_time(jid)}) return ret
python
def _parse_value_node(self, vtype, node): # type: (str, ElementTree.Element) -> Any """ Parses a value node :param vtype: The value type :param node: The value node :return: The parsed value """ kind = node.tag if kind == TAG_XML: # Ra...
python
def apply_to_point(self, point): """ Apply transform to a point Arguments --------- point : list/tuple point to which the transform will be applied Returns ------- list : transformed point Example ------- >>> import a...
python
def get_namespace(name): """Return a :class:`ConfigNamespace` by name, creating the namespace if it does not exist. """ if name not in configuration_namespaces: configuration_namespaces[name] = ConfigNamespace(name) return configuration_namespaces[name]
java
protected boolean isUserRequest() { if (tc.isEntryEnabled()) SibTr.entry(this, tc, "isUserRequest"); if (tc.isEntryEnabled()) SibTr.exit(this, tc, "isUserRequest", ""+isUserRequest); return isUserRequest; }
python
def show_options_help(self): """! @brief Display help for user options.""" for infoName in sorted(options.OPTIONS_INFO.keys()): info = options.OPTIONS_INFO[infoName] if isinstance(info.type, tuple): typename = ", ".join(t.__name__ for t in info.type) e...
python
def pages(): """Load pages.""" p1 = Page( url='/example1', title='My page with default template', description='my description', content='hello default page', template_name='invenio_pages/default.html', ) p2 = Page( url='/example2', title='My page w...
java
private static void checkName(String name, Class<?> type, List<? extends ReferenceData> previousEntries) throws IllegalStateException { if (StringUtils.isNullOrEmpty(name)) { throw new IllegalStateException(type.getSimpleName() + " name cannot be null"); } for (ReferenceD...
python
def add_partition_with_environment_context(self, new_part, environment_context): """ Parameters: - new_part - environment_context """ self.send_add_partition_with_environment_context(new_part, environment_context) return self.recv_add_partition_with_environment_context()
python
def search_dashboard_for_facet(self, facet, **kwargs): # noqa: E501 """Lists the values of a specific facet over the customer's non-deleted dashboards # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass...
python
def _folder_item_css_class(self, analysis_brain, item): """Sets the suitable css class name(s) to `table_row_class` from the item passed in, depending on the properties of the analysis object :param analysis_brain: Brain that represents an analysis :param item: analysis' dictionary coun...
java
private String checkForwardto(final HttpServletRequest request) throws Throwable { String reqpar = request.getParameter("forwardto"); return reqpar; }
java
private String generatePageSQLStatement(boolean tableExists, Map<String, Set<Integer>> dataSourceToUse) { StringBuffer output = new StringBuffer(); // Statement creates table for Template Id -> Page Id output.append("CREATE TABLE IF NOT EXISTS " + GeneratorConstants.TABLE_TPLID_PAGEID + " (" + "t...
python
def find_lambda_condition(decorator_inspection: DecoratorInspection) -> Optional[ConditionLambdaInspection]: """ Inspect the decorator and extract the condition as lambda. If the condition is not given as a lambda function, return None. """ call_node = decorator_inspection.node lambda_node = N...
python
def computePWCorrelationsWithinCol(spikeTrains, removeAutoCorr, cellsPerColumn): """ Computes pairwise correlations from spikeTrains @param spikeTrains (array) spike trains obtained from the activation of cells in the TM the array dimensions are: numCells x timeSteps @param removeAutoCorr (boolean) if t...
python
def me(self): """获取使用特定 cookies 的 Me 实例 :return: cookies对应的Me对象 :rtype: Me """ from .me import Me headers = dict(Default_Header) headers['Host'] = 'zhuanlan.zhihu.com' res = self._session.get(Get_Me_Info_Url, headers=headers) json_data = res.json(...
python
def get_plugins_dists(app, name=None): '''Return a list of Distributions with enabled udata plugins''' if name: plugins = set(e.name for e in iter_all(name) if e.name in app.config['PLUGINS']) else: plugins = set(app.config['PLUGINS']) return [ d for d in known_dists() if...
java
public static base_responses delete(nitro_service client, String serverip[]) throws Exception { base_responses result = null; if (serverip != null && serverip.length > 0) { ntpserver deleteresources[] = new ntpserver[serverip.length]; for (int i=0;i<serverip.length;i++){ deleteresources[i] = new ntpserver...
java
public static <T> SimpleOperation<T> operation(Class<? extends T> type, Operator operator, Expression<?>... args) { return simpleOperation(type, operator, args); }
java
@BetaApi public final Operation deleteSecurityPolicy(ProjectGlobalSecurityPolicyName securityPolicy) { DeleteSecurityPolicyHttpRequest request = DeleteSecurityPolicyHttpRequest.newBuilder() .setSecurityPolicy(securityPolicy == null ? null : securityPolicy.toString()) .build(); ...
python
async def create_scene(self, room_id, name, color_id=0, icon_id=0): """Creates am empty scene. Scenemembers need to be added after the scene has been created. :returns: A json object including scene id. """ name = unicode_to_base64(name) _data = { "scene": {...
java
protected void processRemainingReferences(APMSpanBuilder builder, Reference primaryRef) { // Check if other references for (Reference ref : builder.references) { if (primaryRef == ref) { continue; } // Setup correlation ids for other references ...
java
public String uploadImage(byte[] image, byte[] watermark, String ext, Map<String, String> metaInfo, float opacity, int pos, int margin) { String path = ""; TrackerServer trackerServer = null; StorageClient1 storageClient1 = null; ByteArrayOutputStream thumbOs = new ByteArrayOutputStream(...
python
def is_nullable_list(val, vtype): """Return True if list contains either values of type `vtype` or None.""" return (isinstance(val, list) and any(isinstance(v, vtype) for v in val) and all((isinstance(v, vtype) or v is None) for v in val))
java
@Override public <I> Choice8<A, B, C, D, E, F, G, I> fmap(Function<? super H, ? extends I> fn) { return Monad.super.<I>fmap(fn).coerce(); }
java
public void loadLibrary(Resolver resolver, Node base, Node descriptor, Node properties) throws IOException { Source source; Module module; Library library; File file; addReload(descriptor); source = Source.load(properties, base); library = (Library) Library.TYPE....
python
def _Region1(T, P): """Basic equation for region 1 Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- prop : dict Dict with calculated properties. The available properties are: * v: Specific volume, [m³/kg] ...
java
@SafeVarargs @SuppressWarnings("unchecked") public static <T> Iterable<T> compositeIterable(Iterable<T>...iterables) { Require.nonNull(iterables, "iterables"); final Iterator<T> it; if (iterables.length == 0) { it = Collections.emptyIterator(); } else if (iterables.le...
java
public static boolean directoryContains(final URI directory, final URI child) { final String d = directory.normalize().toString(); final String c = child.normalize().toString(); if (d.equals(c)) { return false; } else { return c.startsWith(d); } }
java
public <T> I addPageNames(Collection<T> webPages, Function<T, String> mapper) { for (T element : webPages) { addPage(WebPage.of(mapper.apply(element))); } return getThis(); }
java
private void printError(String prefix, String msg) { if (nerrors < MaxErrors) { PrintWriter errWriter = getWriter(WriterKind.ERROR); printRawLines(errWriter, prefix + ": " + getText("javadoc.error") + " - " + msg); errWriter.flush(); prompt(); nerrors+...
java
public com.google.api.ads.adwords.axis.v201809.cm.ConversionOptimizerEligibilityRejectionReason[] getRejectionReasons() { return rejectionReasons; }
python
def list_contacts(self, **kwargs): """ List all contacts, optionally filtered by a query. Specify filters as query keyword argument, such as: query= email is abc@xyz.com, query= mobile is 1234567890, query= phone is 1234567890, contacts can be filtered ...
java
protected void setValues(int[] values) { getChronology().validate(this, values); System.arraycopy(values, 0, iValues, 0, iValues.length); }
python
def GetReportData(self, get_report_args, token): """Extract only the operating system type from the active histogram.""" report = rdf_report_plugins.ApiReportData( representation_type=rdf_report_plugins.ApiReportData.RepresentationType .PIE_CHART) graph_series = client_report_utils.FetchMos...
java
public List<Attribute.TypeCompound> getRawTypeAttributes() { return (metadata == null) ? List.<Attribute.TypeCompound>nil() : metadata.getTypeAttributes(); }
python
def add_node(self, graph_node): """Adds a node object to the graph. It takes a node object as its only argument and returns None. """ if not isinstance(graph_node, Node): raise TypeError( 'add_node() received ' + 'a non node class obj...
java
@SafeVarargs public final <T> Stream<T> streamAll(final Class<T> targetClass, final List<String> sqls, final StatementSetter statementSetter, final JdbcSettings jdbcSettings, final Object... parameters) { final JdbcUtil.BiRecordGetter<T, RuntimeException> biRecordGetter = BiRecordGetter.to(ta...
python
def freeze(self): """ Freezes this Config object, disallowing modification or addition of any parameters. """ if getattr(self, '_frozen'): return object.__setattr__(self, "_frozen", True) for k, v in self.__dict__.items(): if isinstance(v, Config) ...
java
@Override public final void narExecute() throws MojoExecutionException, MojoFailureException { // download the dependencies if needed in local maven repository. List<AttachedNarArtifact> attachedNarArtifacts = getAttachedNarArtifacts(libraries); downloadAttachedNars(attachedNarArtifacts); // Warning,...
java
public void setSamplingStatisticsDocuments(java.util.Collection<SamplingStatisticsDocument> samplingStatisticsDocuments) { if (samplingStatisticsDocuments == null) { this.samplingStatisticsDocuments = null; return; } this.samplingStatisticsDocuments = new java.util.Array...
python
def _sentence(self, words): """Generate a sentence""" db = self.database # Generate 2 words to start a sentence with seed = random.randint(0, db['word_count'] - 3) seed_word, next_word = db['words'][seed], db['words'][seed + 1] w1, w2 = seed_word, next_word # Ge...
java
@Override protected boolean semanticallyEquivalent(BioPAXElement element) { if(! (element instanceof Evidence) ) return false; Evidence that = (Evidence) element; // not null (guaranteed by here) boolean hasAllEquivEvidenceCodes = false; if(this.getEvidenceCode().isEmpty()) { if(that.getEvidenceCode().is...
java
public void feedTheWholeTagStructureToGraph(org.jboss.windup.config.tags.TagService tagLoaderService) { Set<Tag> visited = new HashSet<>(); for (Tag tag : tagLoaderService.getRootTags()) { // Sanity check TagModel existing = this.getUniqueByProperty(TagModel.PROP_NA...
python
def remove(name): ''' Remove a Powershell DSC module from the system. :param name: Name of a Powershell DSC module :type name: ``str`` CLI Example: .. code-block:: bash salt 'win01' psget.remove PowerPlan ''' # Putting quotes around the parameter protects against command i...
python
def CreateSessionStart(self): """Creates a session start. Returns: SessionStart: session start attribute container. """ session_start = SessionStart() session_start.artifact_filters = self.artifact_filters session_start.command_line_arguments = self.command_line_arguments session_star...
java
public LiveGraph createLiveGraph(Object handle) { Object wrappedHandle = wrapTopLevelContainer(handle); return new ObjectGraphBuilder(typeMapper, liveCdoFactory).buildGraph(wrappedHandle); }
java
protected List<FacesConfig> applySortingAlgorithm(List<FacesConfig> appConfigResources) throws FacesException { //0. Convert the references into a graph List<Vertex<FacesConfig>> vertexList = new ArrayList<Vertex<FacesConfig>>(); for (FacesConfig config : appConfigResources) { ...
java
public Matrix3x2f set(FloatBuffer buffer) { int pos = buffer.position(); MemUtil.INSTANCE.get(this, pos, buffer); return this; }