language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Date getLastModified(String filename) throws IOException, ServerException { if (filename == null) { throw new IllegalArgumentException("Required argument missing"); } Command cmd = new Command("MDTM", filename); Reply reply = null; try { rep...
python
def plot_contours(self, grid, filled=True, ax=None, labels=None, subplots_kw=dict(), **kwargs): """ Plot equipotentials contours. Computes the potential energy on a grid (specified by the array `grid`). .. warning:: Right now the grid input must be arrays and must ...
java
public synchronized boolean canBeConfigured(HttpContext httpContext) { return canBeConfigured(httpContext, servletModels) && canBeConfigured(httpContext, filterModels.values()) && canBeConfigured(httpContext, eventListenerModels.values()) && canBeConfigured(httpContext, errorPageModels.values()) && ca...
java
public byte[] getRL2Image( Geometry geom, String geomEpsg, int width, int height ) throws Exception { String sql; String rasterName = getName(); if (geomEpsg != null) { sql = "select GetMapImageFromRaster('" + rasterName + "', ST_Transform(ST_GeomFromText('" + geom.toText() + "', " ...
java
public InputStream getAvatar() { URL url = USER_AVATAR_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID()); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); BoxAPIResponse response = request.send(); return response.getBody(); }
java
private JsonWriter close(int empty, int nonempty, String closeBracket) throws IOException { int context = peekScope(); if (context != nonempty && context != empty) { throw new IllegalStateException("Nesting problem."); } if (deferredName != null) { throw new IllegalStateException("Dangling n...
java
public DefaultTableColumn addPropertyColumn(Object headerValue, String property, Class type) { return addColumn(headerValue, property, new PropertyModel(rowModel, property, type)); }
java
public static boolean eq(String s1, String s2, int modifier) { return isEqual(s1, s2, modifier); }
python
def get_collection(self, collection, filter=None, fields=None, page_size=None): """ Returns a specific collection from the asset service with the given collection endpoint. Supports passing through parameters such as... - filters such as "name=Vesuvius" following GEL...
python
def get_effective_domain_id(request): """Gets the id of the default domain. If the requests default domain is the same as DEFAULT_DOMAIN, return None. """ default_domain = get_default_domain(request) domain_id = default_domain.get('id') domain_name = default_domain.get('name') return No...
java
public static @Nonnull Entry<String,JsonElement> field(String key, JsonElement value) { Entry<String, JsonElement> entry = new Entry<String,JsonElement>() { @Override public String getKey() { return key; } @Override public JsonElement...
java
private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(table.length); // Have to use null-terminated list because size might shrink // during iteration for (Iterator iter = entrySet().iterator(); iter.hasNext();)...
python
def get_unaligned_start_coord(self): """ .. warning:: not implemented """ sys.stderr.write("error unimplemented get_unaligned_start_coord\n") sys.exit() if len(self._unaligned)==0: return None return [self._lines[self._unaligned[0]-1]['filestart'],self._lines[self._unaligned[0]-1]['innerstar...
java
public static Map groupBy(Iterable self, List<Closure> closures) { return groupBy(self, closures.toArray()); }
java
@Override protected void deserializeBytes20to23 (final int line) throws InternetSCSIException { connectionID = (line & Constants.FIRST_TWO_BYTES_MASK) >>> Constants.TWO_BYTES_SHIFT; Utils.isReserved(line & Constants.LAST_TWO_BYTES_MASK); }
java
public SerialArrayList<U> add(SerialArrayList<U> right) { return new SerialArrayList<U>(factory, this, right); }
python
def _encrypted_data_keys_hash(hasher, encrypted_data_keys): """Generates the expected hash for the provided encrypted data keys. :param hasher: Existing hasher to use :type hasher: cryptography.hazmat.primitives.hashes.Hash :param iterable encrypted_data_keys: Encrypted data keys to hash :returns: ...
java
protected void registerIbmAlpn(SSLEngine engine, boolean useAlpn) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "registerIbmAlpn entry " + engine); } try { // invoke ALPNJSSEExt.put(engine, String[] protocols) String[] proto...
java
public Node nextNode() { if (currentNode == null) return null; Node result = getFirstChild(currentNode); if (result != null) { currentNode = result; return result; } result = getNextSibling(currentNode); if (result != null) { currentNode = result; return result; } // return parent's...
java
public void setFileContents(final String key, final byte[] contents) { MockFileItem fileItem = new MockFileItem(); fileItem.set(contents); files.put(key, new FileItem[]{fileItem}); }
java
protected CompletionStage<ValidResponse> singleWriteOnRemotePrimary(Address target, DataWriteCommand command) { return rpcManager.invokeCommand(target, command, SingleResponseCollector.validOnly(), rpcManager.getSyncRpcOptions()); }
python
def _make_valid_bounds(self, test_bounds): """ Private method: process input bounds into a form acceptable by scipy.optimize, and check the validity of said bounds. :param test_bounds: minimum and maximum weight of an asset :type test_bounds: tuple :raises ValueError: if...
java
private void addHours(ProjectCalendarDateRanges ranges, Record hoursRecord) { if (hoursRecord.getValue() != null) { String[] wh = hoursRecord.getValue().split("\\|"); try { String startText; String endText; if (wh[0].equals("s")) ...
java
private static int lookup(final TSDB tsdb, final boolean use_data_table, final String[] args) throws Exception { if (!use_data_table) { tsdb.getClient().ensureTableExists( tsdb.getConfig().getString( "tsd.storage.hbase.meta_table"...
java
@Override public void render(final String word, BufferedImage image) { Graphics2D g = image.createGraphics(); RenderingHints hints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); hints.add(new RenderingHints(Renderin...
java
@Override public final ProcessorResult processAttribute(final Arguments arguments, final Element element, final String attributeName) { NestableNode parent = element.getParent(); final String fieldNameExpr = element.getAttributeValue(attributeName); final String fieldName; ...
python
def create(self, handle=None, handle_type=None, **args): """ Creates an ontology based on a handle Handle is one of the following - `FILENAME.json` : creates an ontology from an obographs json file - `obo:ONTID` : E.g. obo:pato - creates an ontology from obolibrary PURL (re...
python
def update_args(self, override_args): """Update the argument used to invoke the application Note that this will also update the dictionary of input and output files. Parameters ----------- override_args : dict dictionary passed to the links """ ...
java
public static void processMessageToMatchSession(HttpMessage message, HttpSession session) { processMessageToMatchSession(message, message.getRequestHeader().getHttpCookies(), session); }
java
public static void readXLSXRuleFile(String xlsxFileName, HashMap<Integer, ContextRule> rules, HashMap<String, TypeDefinition> conceptFeaturesMap, HashMap<String, String> featureDefaultValueMap, HashMa...
java
protected String getDefaultTimeFormatIfNull(Member c2jMemberDefinition, Map<String, Shape> allC2jShapes, String protocolString, Shape parentShape) { String timestampFormat = c2jMemberDefinition.getTimestampFormat(); if (!StringUtils.isNullOrEmpty(timestampFormat)) { failIfInCollection(c2jMe...
java
public BooleanProperty isEmptyProperty() { if (this.isEmpty == null) { this.isEmpty = new SimpleBooleanProperty(this, MathFXAttributeNames.IS_EMPTY); this.isEmpty.bind(Bindings.createBooleanBinding(() -> { final PathIterator2ai<PathElement2ifx> pi = getPathIterator(); while (pi.hasNext()) { final P...
java
public CmsOrganizationalUnit createOrganizationalUnit( CmsObject cms, String ouFqn, String description, int flags, String resourceName) throws CmsException { CmsResource resource = null; if (((flags & CmsOrganizationalUnit.FLAG_WEBUSERS) == 0) || (resourceName !=...
python
def stop_timer(self, request_len, reply_len, server_time=None, exception=False): """ This is a low-level method is called by pywbem at the end of an operation. It completes the measurement for that operation by capturing the needed data, and updates the statistics data...
python
def create_remoteckan(cls, site_url, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, session=None, **kwargs): # type: (str, Optional[str], Optional[str], Optional[str], requests.Session, Any) -> ckanapi.RemoteCKAN """ Create remote CKAN instance fr...
python
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES ...
java
public ListDevicesResult withDevices(DeviceSummary... devices) { if (this.devices == null) { setDevices(new java.util.ArrayList<DeviceSummary>(devices.length)); } for (DeviceSummary ele : devices) { this.devices.add(ele); } return this; }
java
public void setTimex2(FSArray v) { if (Document_Type.featOkTst && ((Document_Type)jcasType).casFeat_timex2 == null) jcasType.jcas.throwFeatMissing("timex2", "de.julielab.jules.types.ace.Document"); jcasType.ll_cas.ll_setRefValue(addr, ((Document_Type)jcasType).casFeatCode_timex2, jcasType.ll_cas.ll_getFSR...
python
def fetch_token(self, **kwargs): """Fetch a new token using the supplied code. :param str code: A previously obtained auth code. """ if 'client_secret' not in kwargs: kwargs.update(client_secret=self.client_secret) return self.session.fetch_token(token_url, **kwargs...
java
public CloudPool get(String poolId, PoolGetOptions poolGetOptions) { return getWithServiceResponseAsync(poolId, poolGetOptions).toBlocking().single().body(); }
python
def _set_config_mode(self, v, load=False): """ Setter method for config_mode, mapped from YANG variable /interface/fc_port/config_mode (interface-fc-config-mode-type) If this variable is read-only (config: false) in the source YANG file, then _set_config_mode is considered as a private method. Backe...
java
public static String rtrimWildcardTokens(String input) { String[] tokens = tokenizePathAsArray(input); StringBuilder sb = new StringBuilder(); for (int i = 0; i < tokens.length; i++) { if (hasWildcards(tokens[i])) { break; } if (i > 0 && sb.cha...
python
def _parse_g_dir(repo, gdirpath): """parses a repo directory two-levels deep""" for f in repo.get_contents(gdirpath): if f.type == "dir": for sf in repo.get_contents(f.path): yield sf else: yield f
java
public void shutdown() { // Prevent new entries from being added ... this.addEntries.set(false); // Mark the cursor as being finished; this will stop all consumers from waiting for a batch ... this.cursor.complete(); // Each of the consumer threads will complete the batch they'...
java
static byte[] generateClassBytes(String proxyClassName, Class proxyInterface, Method[] proxyMethods, EJBMethodInfoImpl[] methodInfos, String ejbClassName, ...
python
def object_emitter(target, source, env, parent_emitter): """Sets up the PCH dependencies for an object file.""" validate_vars(env) parent_emitter(target, source, env) # Add a dependency, but only if the target (e.g. 'Source1.obj') # doesn't correspond to the pre-compiled header ('Source1.pch'). ...
python
def tag_and_push(context): """Tags your git repo with the new version number""" tag_option = '--annotate' if probe.has_signing_key(context): tag_option = '--sign' shell.dry_run( TAG_TEMPLATE % (tag_option, context.new_version, context.new_version), context.dry_run, ) sh...
java
@Override public void removeByUuid_C(String uuid, long companyId) { for (CommercePriceList commercePriceList : findByUuid_C(uuid, companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(commercePriceList); } }
python
def as_index(keys, axis=semantics.axis_default, base=False, stable=True, lex_as_struct=False): """ casting rules for a keys object to an index object the preferred semantics is that keys is a sequence of key objects, except when keys is an instance of tuple, in which case the zipped elements of the...
python
def _find_by_nsp(self, browser, criteria, tag, constraints): """Find element matches by iOSNsPredicateString.""" return self._filter_elements( browser.find_elements_by_ios_predicate(criteria), tag, constraints)
python
def encode(self, b64=False, always_bytes=True): """Encode the packet for transmission.""" if self.binary and not b64: encoded_packet = six.int2byte(self.packet_type) else: encoded_packet = six.text_type(self.packet_type) if self.binary and b64: ...
java
public Object invokeVisit(Object visitor, Object argument) { Assert.notNull(visitor, "The visitor to visit is required"); // Perform call back on the visitor through reflection. Method method = getMethod(visitor.getClass(), argument); if (method == null) { if (logger.isWarnEnabled()) { logger.warn("No me...
java
public List<CmsVisitEntry> readVisits(CmsDbContext dbc, String poolName, CmsVisitEntryFilter filter) throws CmsDataAccessException { List<CmsVisitEntry> entries = new ArrayList<CmsVisitEntry>(); Connection conn = null; PreparedStatement stmt = null; ResultSet res = null; t...
java
public StringArray getGeneSymbolList() { if (ManualDescriptor_Type.featOkTst && ((ManualDescriptor_Type)jcasType).casFeat_geneSymbolList == null) jcasType.jcas.throwFeatMissing("geneSymbolList", "de.julielab.jules.types.pubmed.ManualDescriptor"); return (StringArray)(jcasType.ll_cas.ll_getFSForRef(jcasTyp...
java
private static IAnnotationBinding getAnnotationBinding( IAnnotationBinding[] annotations, Class<?> annotationClass) { if (annotationClass == null) { throw new NullPointerException(); } return getAnnotationBinding(annotations, annotationClass.getCanonicalName()); }
python
def _inspect_class(cls, subclass): """ Args: cls(:py:class:`Plugin`): Parent class subclass(:py:class:`Plugin`): Subclass to evaluate Returns: Result: Named tuple Inspect subclass for inclusion Values for errorcode: * 0: No error Error codes between 0 and...
python
def bulk_index(cls, documents, id_field='id', es=None, index=None): """Adds or updates a batch of documents. :arg documents: List of Python dicts representing individual documents to be added to the index .. Note:: This must be serializable into JSON. :...
java
public Class<?> reflectClass(final String className) { Preconditions.checkArgument(className != null && className.trim().length() > 0, "className cannot be null or empty"); return provider.getClassReflectionProvider(className).reflectClass(); }
java
protected int getOptionIndex(final Object option) { int optionCount = 0; List<?> options = getOptions(); if (options != null) { for (Object obj : getOptions()) { if (obj instanceof OptionGroup) { List<?> groupOptions = ((OptionGroup) obj).getOptions(); int groupIndex = groupOptions.indexOf(opti...
python
def greenkhorn(a, b, M, reg, numItermax=10000, stopThr=1e-9, verbose=False, log=False): """ Solve the entropic regularization optimal transport problem and return the OT matrix The algorithm used is based on the paper Near-linear time approximation algorithms for optimal transport via Sinkhorn iterati...
java
public static void validateClusterPartitionState(final Cluster subsetCluster, final Cluster supersetCluster) { if(!supersetCluster.getNodeIds().containsAll(subsetCluster.getNodeIds())) { throw new VoldemortException("Superset cluster does not cont...
java
public static boolean isEqualIgnoreCase(String pStr1, String pStr2) { if (pStr1 == null && pStr2 == null) { return true; } else if (pStr1 == null || pStr2 == null) { return false; } else if (pStr1.equalsIgnoreCase(pStr2)) { return true; } retur...
java
public EventsBatch withEvents(java.util.Map<String, Event> events) { setEvents(events); return this; }
python
def blockgen(blocks, shape): """Generate a list of slice tuples to be used by combine. The tuples represent regions in an N-dimensional image. :param blocks: a tuple of block sizes :param shape: the shape of the n-dimensional array :return: an iterator to the list of tuples of slices Example:...
python
def search_aikif(txt, formatHTML=True): """ search for text - currently this looks in all folders in the root of AIKIF but that also contains binaries so will need to use the agent_filelist.py to specify the list of folders. NOTE - this needs to use indexes rather than full search each time ...
java
public static String join(String _delimiter, String[] _strings) { return join(_delimiter, Arrays.asList(_strings)); }
python
def setVerticalAxis(self, axis): """ Sets the vertical axis for this chart. :param axis | <XChartAxis> """ self._verticalAxis = axis if axis: axis.setOrientation(Qt.Vertical) self.uiYAxisVIEW.setFixedWidth(axis.minimumLabelWi...
python
def get_output(self, output_files, clear=True): "Get the output files as an id indexed dict." patt = re.compile(r'(.*?)-semantics.*?') for outpath in output_files: if outpath is None: logger.warning("Found outpath with value None. Skipping.") continue ...
python
def main_module(self): """Return the main module to which the receiver belongs.""" if self.i_module.keyword == "submodule": return self.i_module.i_ctx.get_module( self.i_module.i_including_modulename) return self.i_module
python
def remainder(self, max_value=None): """ Returns the time remaining for the timeout, or *max_value* if that remainder is larger. """ if self.value is None: return max_value remainder = self.value - (time.clock() - self.start) if remainder < 0.0: return 0.0 elif max_value is ...
java
final boolean isExpired() throws SevereMessageStoreException { // 182086 if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "isExpired"); if (isAvailable() && internalCanExpire()) { // we can only expire if we are available ...
java
public void copyResourceToProject(String resourcename) throws CmsException { CmsResource resource = readResource(resourcename, CmsResourceFilter.ALL); copyResourceToProject(resource); }
java
public JavaScriptActionBuilder javascript(Resource script, Charset charset) { JavaScriptAction action = new JavaScriptAction(); try { action.setScript(FileUtils.readToString(script, charset)); } catch (IOException e) { throw new CitrusRuntimeException("Failed to read scri...
java
@Override public ListAgentsResult listAgents(ListAgentsRequest request) { request = beforeClientExecution(request); return executeListAgents(request); }
java
public List<Relationship> getNextRelationships() { final List<Relationship> nextRelationships = new LinkedList<Relationship>(); for (final Relationship r : relationships) { if (r.getType() == RelationshipType.NEXT) { nextRelationships.add(r); } } r...
python
def transaction(self, callback): """Executes a function in a transaction. The function gets passed this Connection instance as an (optional) parameter. If an exception occurs during execution of the function or transaction commit, the transaction is rolled back and the exception re-thr...
python
def _filter_fields(self, filter_function): """ Utility to iterate through all fields (super types first) of a type. :param filter: A function that takes in a Field object. If it returns True, the field is part of the generated output. If False, it is omitted. """...
python
def intervals(self, startdate, enddate, parseinterval=None): '''Given a ``startdate`` and an ``enddate`` dates, evaluate the date intervals from which data is not available. It return a list of two-dimensional tuples containing start and end date for the interval. The list could cont...
python
def process_sparser_output(output_fname, output_fmt='json'): """Return a processor with Statements extracted from Sparser XML or JSON Parameters ---------- output_fname : str The path to the Sparser output file to be processed. The file can either be JSON or XML output from Sparser, wit...
java
public static long getTimeMillisWithNano(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, String zoneId) { return ZonedDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond, getZoneId(zoneId)).toInstant().toEpochMi...
python
def relaxNGNewParserCtxt(URL): """Create an XML RelaxNGs parse context for that file/resource expected to contain an XML RelaxNGs file. """ ret = libxml2mod.xmlRelaxNGNewParserCtxt(URL) if ret is None:raise parserError('xmlRelaxNGNewParserCtxt() failed') return relaxNgParserCtxt(_obj=ret)
java
public OsmLayer createOsmLayer(String id, int nrOfLevels, String url) { OsmLayer layer = new OsmLayer(id, createOsmTileConfiguration(nrOfLevels)); layer.addUrl(url); return layer; }
python
def write(self,buf): """ Write command to blink(1), low-level internal use Send USB Feature Report 0x01 to blink(1) with 8-byte payload Note: arg 'buf' must be 8 bytes or bad things happen """ log.debug("blink1write:" + ",".join('0x%02x' % v for v in buf)) self.de...
python
def _maintain_dep_graph(self, p_todo): """ Makes sure that the dependency graph is consistent according to the given todo. """ dep_id = p_todo.tag_value('id') # maintain dependency graph if dep_id: self._parentdict[dep_id] = p_todo self._de...
python
def _construct_bower_command(bower_command): ''' Create bower command line string ''' if not bower_command: raise CommandExecutionError( 'bower_command, e.g. install, must be specified') cmd = ['bower'] + shlex.split(bower_command) cmd.extend(['--config.analytics', 'false', ...
java
public static void setTextInfoTranslationEnabled(boolean textInfoTranslationEnabled, Locale locale) { com.ibm.ws.pmi.stat.StatsImpl.setEnableNLS(textInfoTranslationEnabled, locale); }
java
public DBClusterSnapshotAttributesResult withDBClusterSnapshotAttributes(DBClusterSnapshotAttribute... dBClusterSnapshotAttributes) { if (this.dBClusterSnapshotAttributes == null) { setDBClusterSnapshotAttributes(new java.util.ArrayList<DBClusterSnapshotAttribute>(dBClusterSnapshotAttributes.length)...
python
def get_raw_input(description, default=False): """Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input. """ additional = ' (default: ...
java
@Pure @Override public PathIterator3f getPathIterator(Transform3D transform) { if (transform == null) { return new CopyPathIterator3f(); } return new TransformPathIterator3f(transform); }
python
def get_project(self, project_short_name): """Return project object.""" project = pbclient.find_project(short_name=project_short_name, all=self.all) if (len(project) == 1): return project[0] else: raise ProjectNotFound(proje...
python
def get_rendition_url(request, image_id, target_width=0, target_height=0): ''' get a rendition url if the rendition does nto exist it will be created in the storage if dimensions do not fit master's aspect ratio then image will be cropped with a centered anchor if one dimensions is omitted (0)...
java
public static RealMatrix colSubtract (RealMatrix matrix, double[] vector) { // Declare and initialize the new matrix: double[][] retval = new double[matrix.getRowDimension()][matrix.getColumnDimension()]; // Iterate over rows: for (int col = 0; col < retval.length; col++) { ...
python
def get_flag_value(self, name, default): # pylint: disable=invalid-name """Returns the value of a flag (if not None) or a default value. Args: name: str, the name of a flag. default: Default value to use if the flag value is None. Returns: Requested flag value or default. """ v...
java
private void initPatternControllers() { m_patternControllers.put(PatternType.NONE, new CmsPatternPanelNoneController()); m_patternControllers.put(PatternType.DAILY, new CmsPatternPanelDailyController(m_model, this)); m_patternControllers.put(PatternType.WEEKLY, new CmsPatternPanelWeeklyCont...
python
def ordering(self, type): """ Get the attribute ordering defined in the specified XSD type information. @param type: An XSD type object. @type type: SchemaObject @return: An ordered list of attribute names. @rtype: list """ result = [] for ...
python
def _filter_image(self, url): "The param is the image URL, which is returned if it passes all the filters." return reduce(lambda f, g: f and g(f), [ filters.AdblockURLFilter()(url), filters.NoImageFilter(), filters.SizeImageFilter(), filters.MonoI...
java
public EClass getIfcAmountOfSubstanceMeasure() { if (ifcAmountOfSubstanceMeasureEClass == null) { ifcAmountOfSubstanceMeasureEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(656); } return ifcAmountOfSubstanceMeasureEClass; }
java
public EventBus bindSync(Class<? extends EventObject> eventType, ActEventListener eventListener) { return _bind(actEventListeners, eventType, eventListener, 0); }
java
@Override public CommercePriceList fetchByC_ERC(long companyId, String externalReferenceCode, boolean retrieveFromCache) { Object[] finderArgs = new Object[] { companyId, externalReferenceCode }; Object result = null; if (retrieveFromCache) { result = finderCache.getResult(FINDER_PATH_FETCH_BY_C_ERC, ...
java
public static JMDictSense create() { if (index >= instances.size()) { instances.add(new JMDictSense()); } return instances.get(index++); }