language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public java.lang.String getExtends() { java.lang.Object ref = extends_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.i...
java
public static String getExtension(String uri) { if (uri == null) { return null; } int dot = uri.lastIndexOf("."); if (dot >= 0) { return uri.substring(dot); } else { // No extension. return ""; } }
java
public static Function<Object,Calendar> attrOfCalendar(final String attributeName) { return new Get<Object,Calendar>(Types.CALENDAR, attributeName); }
python
def __extractOntologies(self, exclude_BNodes = False, return_string=False): """ returns Ontology class instances [ a owl:Ontology ; vann:preferredNamespacePrefix "bsym" ; vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ], """ out = [] ...
python
def delete(self, path=None, url_kwargs=None, **kwargs): """ Sends a PUT request. :param path: The HTTP path (either absolute or relative). :param url_kwargs: Parameters to override in the generated URL. See `~hyperlink.URL`. :param **kwargs: O...
java
private int clearGeometryIndices() { int deleted = 0; DeleteBuilder<GeometryIndex, GeometryIndexKey> db = geometryIndexDao .deleteBuilder(); try { db.where().eq(GeometryIndex.COLUMN_TABLE_NAME, tableName); PreparedDelete<GeometryIndex> deleteQuery = db.prepare(); deleted = geometryIndexDao.delete(del...
java
private static void listProjectProperties(ProjectFile file) { SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm z"); ProjectProperties properties = file.getProjectProperties(); Date startDate = properties.getStartDate(); Date finishDate = properties.getFinishDate(); String fo...
java
private void updateMeta(BundleMeta meta) { final int cols = meta.size(); densecols = new NumberVector.Factory<?>[cols]; for(int i = 0; i < cols; i++) { if(TypeUtil.SPARSE_VECTOR_VARIABLE_LENGTH.isAssignableFromType(meta.get(i))) { throw new AbortException("Filtering sparse vectors is not yet s...
java
private JsonSimple getConfigFromStorage(String oid) { String configOid = null; String configPid = null; // Get our object and look for its config info try { DigitalObject object = storage.getObject(oid); Properties metadata = object.getMetadata(); configOid = metadata.getProperty("jsonConfigOid"); ...
python
def add(self, *args): """ This function adds strings to the keyboard, while not exceeding row_width. E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]} when row_width is set to 1. When row_width is set to 2, the following is the r...
java
double bytesPerSecond(double byteCount, double durationNano) { if (byteCount < 0 || durationNano < 0) throw new IllegalArgumentException(); if (durationNano == 0) { durationNano = 1.0; // defend against division by zero if (log.isDebugEnabled()) { lo...
python
def run(self, *pipelines, **kwargs): """ Connects all pipelines to that study's repository and runs them in the same NiPype workflow Parameters ---------- pipeline(s) : Pipeline, ... The pipeline to connect to repository required_outputs : list[set[st...
java
URL parseLocalRefUrl( final HttpServletRequest request, final String refUrl) { URL rslt = null; // default if (StringUtils.isNotBlank(refUrl)) { try { final URL context = new URL(request.getRequestURL().toString()); final URL location = new URL(con...
java
public double distance(Vector3ic v) { return distance(v.x(), v.y(), v.z()); }
java
private boolean processQueryEventFilter(EventFilter filter, EntryEventType eventType, Data dataKey, Object oldValue, Object dataValue, String mapNameOrNull) { Object testValue; if (eventType == REMOVED || eventType == EVICTED || eventType == EXPIRED) { ...
python
def search_records(self, domain, record_type, name=None, data=None): """ Returns a list of all records configured for the specified domain that match the supplied search criteria. """ return domain.search_records(record_type=record_type, name=name, data=data)
python
def rank( self, axis=0, method="average", numeric_only=None, na_option="keep", ascending=True, pct=False, ): """ Compute numerical data ranks (1 through n) along axis. Equal values are assigned a rank that is the [method] of ...
java
public void marshall(GetApiRequest getApiRequest, ProtocolMarshaller protocolMarshaller) { if (getApiRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getApiRequest.getApiId(), APIID_BINDING)...
java
@Override public void rewriteHudsonWar(File by) throws IOException { File dest = getHudsonWar(); // this should be impossible given the canRewriteHudsonWar method, // but let's be defensive if(dest==null) throw new IOException("jenkins.war location is not known."); // backi...
java
void setAttribute(File file, String attribute, Object value) { state.checkOpen(); // TODO(cgdecker): Change attribute stuff to avoid the sad boolean parameter attributes.setAttribute(file, attribute, value, false); }
java
public Interval toInterval(DateTimeZone zone) { zone = DateTimeUtils.getZone(zone); DateTime start = toLocalDate(1).toDateTimeAtStartOfDay(zone); DateTime end = plusMonths(1).toLocalDate(1).toDateTimeAtStartOfDay(zone); return new Interval(start, end); }
java
private URI datasetURNtoURI(String datasetURN) { try { return new URI(PathUtils.mergePaths(new Path(this.storeRoot), new Path(datasetURN)).toString()); }catch (URISyntaxException e) { log.error("Dataset with URN:" + datasetURN + " cannot be converted into URI. Skip the dataset"); return null; ...
java
public static String ensureRight(final String value, final String suffix, boolean caseSensitive) { validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER); return endsWith(value, suffix, caseSensitive) ? value : append(value, suffix); }
python
def rownumbers(self, table=None): """Return a list containing the row numbers of this table. This method can be useful after a selection or a sort. It returns the row numbers of the rows in this table with respect to the given table. If no table is given, the original table is used. ...
python
def sql_flush(self, style, tables, sequences, allow_cascade=False): """ Returns a list of SQL statements required to remove all data from the given database tables (without actually removing the tables themselves). The `style` argument is a Style object as returned by either ...
java
public <T> T access(Class<T> clazz) { if ( configuration.getClass().equals(clazz) ) { return clazz.cast(configuration); } try { return clazz.cast(fieldCache.get(clazz).get(configuration)); } catch ( Exception e ) { ...
java
public List<Token> scan() { while (peek() != EOF) { if (peek() == '#') { if (scanDire()) { continue ; } if (scanSingleLineComment()) { continue ; } if (scanMultiLineComment()) { continue ; } if (scanNoParse()) { continue ; } } scanText(...
java
public void set(E entity, Object value) { Object object = entity; for (int i = 0; i < path().size() - 1; i++) { try { Field field = object.getClass().getDeclaredField(path().get(i)); field.setAccessible(true); object = field.get(object); } catch (Exception e) { throw new UncheckedException(...
python
def inspect_node_neighborhood(nlinks, msinds, node_msindex): """ Get information about one node in graph :param nlinks: neighboorhood edges :param msinds: indexes in 3d image :param node_msindex: int, multiscale index of selected voxel :return: node_neighboor_edges_and_weights, node_neighboor_s...
python
def _get_xephem_orbital_elements( self): """*get xephem orbital elements* **Key Arguments:** - ``xephemOE`` -- a list of xephem database format strings for use with pyephem """ self.log.info('starting the ``_get_xephem_orbital_elements`` method') print "...
python
def weave(*iterables): r"""weave(seq1 [, seq2] [...]) -> iter([seq1[0], seq2[0] ...]). >>> list(weave([1,2,3], [4,5,6,'A'], [6,7,8, 'B', 'C'])) [1, 4, 6, 2, 5, 7, 3, 6, 8] Any iterable will work. The first exhausted iterable determines when to stop. FIXME rethink stopping semantics. >>> list...
java
@Override public void close() throws IOException { if (!closed) { try { if (!eof && state != CHUNK_INVALID) { // read and discard the remainder of the message final byte[] buff = new byte[BUFFER_SIZE]; try { ...
java
private final void _prependOrWriteCharacterEscape(char ch, int escCode) throws IOException, JsonGenerationException { if (escCode >= 0) { // \\N (2 char) if (_outputTail >= 2) { // fits, just prepend int ptr = _outputTail - 2; _outputHead = ptr; ...
python
def run(self, request): """ Introspects all of the actions on the server and returns their documentation. :param request: The request object :type request: EnrichedActionRequest :return: The response """ if request.body.get('action_name'): return sel...
java
public <T> T convert(final Object source, final Class<T> targetclass) { if (source == null) { return null; } final Class<?> sourceclass = source.getClass(); if (targetclass.isPrimitive() && String.class.isAssignableFrom(sourceclass)) { return (T) parsePrimitive(s...
java
public void marshall(SetIdentityPoolRolesRequest setIdentityPoolRolesRequest, ProtocolMarshaller protocolMarshaller) { if (setIdentityPoolRolesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
java
public boolean isFile(final VirtualFile mountPoint, final VirtualFile target) { final VirtualFile assemblyFile = assembly.getFile(mountPoint, target); return assemblyFile != null && assemblyFile.isFile(); }
java
@Override public AssociateTeamMemberResult associateTeamMember(AssociateTeamMemberRequest request) { request = beforeClientExecution(request); return executeAssociateTeamMember(request); }
python
def is_sorted(self, ranks=None): """ Checks whether the stack is sorted. :arg dict ranks: The rank dict to reference for checking. If ``None``, it will default to ``DEFAULT_RANKS``. :returns: Whether or not the cards are sorted. """ ...
java
public static final Representation Csv(String text){ return new ImmutableRep(CONTENT_TYPE_CSV, new ByteArrayInputStream(getBytes(text, MOST_WIDELY_SUPPORTED_ENCODING))); }
python
def main(client, adgroup_id): """Runs the example.""" adgroup_criterion_service = client.GetService( 'AdGroupCriterionService', version='v201809') helper = ProductPartitionHelper(adgroup_id) # The most trivial partition tree has only a unit node as the root, e.g.: # helper.CreateUnit(bid_amount=100000...
java
public Map<K, V> loadAll(Iterable<? extends K> keys, Executor executor) throws Exception { throw new UnsupportedOperationException(); }
java
@SuppressWarnings("WeakerAccess") public ApiFuture<List<String>> listTablesAsync() { ListTablesRequest request = ListTablesRequest.newBuilder() .setParent(NameUtil.formatInstanceName(projectId, instanceId)) .build(); // TODO(igorbernstein2): try to upstream pagination spooling...
java
private Map<String, SpringResource> analyzeController(Class<?> controllerClazz, Map<String, SpringResource> resourceMap, String description) { String[] controllerRequestMappingValues = SpringUtils.getControllerResquestMapping(controllerClazz); // Iterate over all value attributes of the class-level RequestMap...
python
def all_intersections(nodes_first, nodes_second): r"""Find the points of intersection among a pair of curves. .. note:: This assumes both curves are :math:`\mathbf{R}^2`, but does not **explicitly** check this. However, functions used here will fail if that assumption fails. Args: ...
java
public FlowLogInformationInner getFlowLogStatus(String resourceGroupName, String networkWatcherName, String targetResourceId) { return getFlowLogStatusWithServiceResponseAsync(resourceGroupName, networkWatcherName, targetResourceId).toBlocking().last().body(); }
java
@Override List<String> getRequestParts() { List<String> ret = super.getRequestParts(); ret.add(operation); if (arguments.size() > 0) { for (int i = 0; i < arguments.size(); i++) { ret.add(serializeArgumentToRequestPart(arguments.get(i))); } } ...
java
private void releaseDisplayView() { if (mDisplayView instanceof GLCameraEncoderView) { ((GLCameraEncoderView) mDisplayView).releaseCamera(); } else if (mDisplayView instanceof GLCameraView) ((GLCameraView) mDisplayView).releaseCamera(); }
java
private int subParseNumericZone(String text, int start, int sign, int count, boolean colonRequired, CalendarBuilder calb) { int index = start; parse: try { char c = text.charAt(index++); // Parse hh int hours; if ...
python
def create_application(server, root_url): """ WSGI adapter. It creates a simple WSGI application, that can be used with any WSGI server. The arguments are: #. ``server`` is a pyws server object, #. ``root_url`` is an URL to which the server will be bound. An application created by the function...
python
def get_preferences(self): """ Gets preferences for certain display variables from zeq_gui_preferences. """ # default preferences = {} preferences['gui_resolution'] = 100. preferences['show_Zij_treatments'] = True preferences['show_Zij_treatments_s...
java
public void addProxy(String protocol, String host, int port, String username, String password) { Proxy proxy = new Proxy(protocol, host, port, username, password); proxies.add(proxy); }
python
def paint(self, painter, option, widget): """ Overloads the default QGraphicsItem paint event to update the \ node when necessary and call the draw method for the node. :param painter <QPainter> :param option <QStyleOptionGraphicsItem> :param ...
java
public static String uncompressString(byte[] input, int offset, int length, String encoding) throws IOException, UnsupportedEncodingException { byte[] uncompressed = new byte[uncompressedLength(input, offset, length)]; uncompress(input, offset, length, uncompressed, 0); ...
java
public Optional<T> minByDouble(ToDoubleFunction<? super T> keyExtractor) { return Box.asOptional(reduce(null, (ObjDoubleBox<T> acc, T t) -> { double val = keyExtractor.applyAsDouble(t); if (acc == null) return new ObjDoubleBox<>(t, val); if (Double.compare(val...
python
def create_subnetwork(kwargs=None, call=None): ''' ... versionadded:: 2017.7.0 Create a GCE Subnetwork. Must specify name, cidr, network, and region. CLI Example: .. code-block:: bash salt-cloud -f create_subnetwork gce name=mysubnet network=mynet1 region=us-west1 cidr=10.0.0.0/24 descrip...
java
public static boolean isValidJsonValue( Object value ) { if( JSONNull.getInstance() .equals( value ) || value instanceof JSON || value instanceof Boolean || value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long || value instanceof ...
python
def _append_object_entry(obj, list_name, entry): # type: (Any, str, Any) -> None """ Appends the given entry in the given object list. Creates the list field if needed. :param obj: The object that contains the list :param list_name: The name of the list member in *obj* :param entry: The ent...
python
def like_button_tag(context): """ This tag will check to see if they have the FACEBOOK_APP_ID setup correctly in the django settings, if so then it will pass the data along to the intercom_tag template to be displayed. If something isn't perfect we will return False, which will then not ...
java
public static FedoraAPIM getStub(String protocol, String host, int port, String username, String password) throws MalformedURLException, Service...
python
def construct_multi_parameter_validators(parameters, context): """ Given an iterable of parameters, returns a dictionary of validator functions for each parameter. Note that this expects the parameters to be unique in their name value, and throws an error if this is not the case. """ validators...
java
public TaskTypesImpl using(Workspace currentWorkspace, Project currentProject) { this.currentWorkspace = currentWorkspace; this.currentProject = currentProject; return this; }
java
public void loadClassFromByteCodes(Map<String, byte[]> inputByteCodes) { if (inputByteCodes == null || inputByteCodes.isEmpty()) { throw new IllegalArgumentException("byteCodes can not be null"); } for (Map.Entry<String, byte[]> byteCode : inputByteCodes.entrySet()) { b...
python
def multi_buffer_help(): """Help message for multi buffer dialog. .. versionadded:: 4.0.0 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) ...
java
public OperationFuture<List<DataCenter>> claim(DataCenter... dataCenters) { return claim(Arrays.asList(dataCenters)); }
python
def H_acceptor_count(mol): """Hydrogen bond acceptor count """ mol.require("Valence") return sum(1 for _, a in mol.atoms_iter() if a.H_acceptor)
java
protected void addDefaultCommands(Bootstrap<T> bootstrap) { bootstrap.addCommand(new ServerCommand<>(this)); bootstrap.addCommand(new CheckCommand<>(this)); }
java
public static InetSocketAddress createAddress(String host, int port) { if (StrUtil.isBlank(host)) { return new InetSocketAddress(port); } return new InetSocketAddress(host, port); }
python
def _val_to_str(self, value): """Converts the value to a string that will be handled correctly by the confobj :param value: the value to parse :type value: something configobj supports :returns: str :rtype: str :raises: None When the value is a list, it will be ...
python
def fsliceafter(astr, sub): """Return the slice after at sub in string astr""" findex = astr.find(sub) return astr[findex + len(sub):]
java
public void printCoordinate(int[] row, int[] column, float[] dataR, float[] dataI, int offset) { int size = row.length; if (size != column.length || size != dataR.length || size != dataI.length) throw new IllegalArgumentException( "All arrays m...
python
def setup_logging(options=None): """Configure logging based on options.""" level = logging.DEBUG if options is not None and options.debug \ else logging.WARNING console = logging.StreamHandler() console.setLevel(level) formatter = logging.Formatter('%(name)s: %(levelname)-8s %(message)s') ...
python
def FileEntryExistsByPathSpec(self, path_spec): """Determines if a file entry for a path specification exists. Args: path_spec (PathSpec): path specification. Returns: bool: True if the file entry exists. """ # Opening a file by inode number is faster than opening a file by location. ...
java
private final BeanProperty toBeanProperty(Object base, Object property) { BeanProperties beanProperties = cache.get(base.getClass()); if (beanProperties == null) { BeanProperties newBeanProperties = new BeanProperties(base.getClass()); beanProperties = cache.putIfAbsent(base.getClass(), newBeanProperties); ...
python
def sparse_geostatistical_prior_builder(pst, struct_dict,sigma_range=4,verbose=False): """ a helper function to construct a full prior covariance matrix using a mixture of geostastical structures and parameter bounds information. The covariance of parameters associated with geostatistical structures is defi...
python
def requires_gurobipy(_has_gurobi): ''' Decorator function which takes a boolean _has_gurobi as an argument. Use decorate any functions which require gurobi. Raises an import error at runtime if gurobi is not present. Note that all runtime errors should be avoided in the working code, using brut...
java
private void redrawScale() { calculateBestFit(1 / mapPresenter.getViewPort().getResolution()); scaleBarElement.setInnerText(formatUnits(widthInUnits)); scaleBarElement.getStyle().setWidth(widthInPixels, Style.Unit.PX); getElement().getStyle().setWidth(widthInPixels + 10, Style.Unit.PX); }
java
public static File createFileBalancingDirectoryDescriptor(File workingDirectory, String fileName, int depth, int cellWidth) { if (depth < 0) { throw new IllegalArgumentException("depth must be greater or equal to 0"); } if (cellWidth < 1) { throw new IllegalArgumentException("cellWidth must be greater ...
python
def strobogrammatic_in_range(low, high): """ :type low: str :type high: str :rtype: int """ res = [] count = 0 low_len = len(low) high_len = len(high) for i in range(low_len, high_len + 1): res.extend(helper2(i, i)) for perm in res: if len(perm) == low_len and...
java
@SuppressWarnings({"WeakerAccess", "unused"}) // For library users public void registerFilters(@NonNull ViewGroup rootView) { final List<AlgoliaFilter> filterViews = LayoutViews.findByClass(rootView, AlgoliaFilter.class); if (filterViews.isEmpty()) { throw new IllegalStateException(Strin...
java
private JSType getNativeWildcardType() { if (isAllType) { return registry.getNativeType(ALL_TYPE); } else if (isNativeUnknownType) { if (areAllUnknownsChecked) { return registry.getNativeType(CHECKED_UNKNOWN_TYPE); } else { return registry.getNativeType(UNKNOWN_TYPE); } ...
python
def program_rtr_default_gw(self, tenant_id, rout_id, gw): """Program the default gateway of a router. """ args = ['route', 'add', 'default', 'gw', gw] ret = self.program_rtr(args, rout_id) if not ret: LOG.error("Program router returned error for %s", rout_id) retu...
java
public void getFeature(int lat, int lon) { info("*** GetFeature: lat={0} lon={1}", lat, lon); Point request = Point.newBuilder().setLatitude(lat).setLongitude(lon).build(); Feature feature; try { feature = blockingStub.getFeature(request); if (testHelper != null) { testHelper.onMes...
java
protected final void abortIfNeeded() { if (shouldAbort()) { try { abort(); // execute subclass specific abortion logic } catch (IOException e) { LogFactory.getLog(getClass()).debug("FYI", e); } throw new AbortedException(); ...
java
public static boolean isSorted(int[] nums) { boolean desc = nums[0] - nums[nums.length - 1] >= 0; for (int i = 0; i < nums.length - 1; i++) { if (!desc && nums[i] > nums[i + 1]) { return false; } if (desc && nums[i] < nums[i + 1]) { ret...
python
def set_transform(self, name, transform): """ Set the transform for one of the manager's objects. This replaces the prior transform. Parameters ---------- name : str An identifier for the object already in the manager transform : (4,4) float A...
python
def run(pcap): """ Runs all configured IDS instances against the supplied pcap. :param pcap: File path to pcap file to analyse :returns: Dict with details and results of run/s """ start = datetime.now() errors = [] status = STATUS_FAILED analyses = [] pool = ThreadPool(MAX_THREA...
java
public <T> T delete(final Class<T> type, @DelegatesTo(HttpConfig.class) final Closure closure) { return type.cast(interceptors.get(HttpVerb.DELETE).apply(configureRequest(type, HttpVerb.DELETE, closure), this::doDelete)); }
java
public static base_response add(nitro_service client, forwardingsession resource) throws Exception { forwardingsession addresource = new forwardingsession(); addresource.name = resource.name; addresource.network = resource.network; addresource.netmask = resource.netmask; addresource.acl6name = resource.acl6na...
java
public ManagedEntity[] searchManagedEntities(String[][] typeinfo, boolean recurse) throws InvalidProperty, RuntimeFault, RemoteException { ObjectContent[] ocs = retrieveObjectContents(typeinfo, recurse); return createManagedEntities(ocs); }
python
def Construct(self): # pylint: disable-msg=C0103 """Construct a cuboid from a GDML file without sensitive detector""" # Parse the GDML self.gdml_parser.Read(self.filename) self.world = self.gdml_parser.GetWorldVolume() self.log.info("Materials:") self.log.info(G4.G4Mate...
java
public Seq<E> intersect(final Seq<E> seq) { return union(seq).filter(e -> contains(e) && seq.contains(e)); }
java
@Override public CreateApiMappingResult createApiMapping(CreateApiMappingRequest request) { request = beforeClientExecution(request); return executeCreateApiMapping(request); }
java
@Override public void deserializeInstance(SerializationStreamReader streamReader, OWLLiteralImplFloat instance) throws SerializationException { deserialize(streamReader, instance); }
java
public List<ElementType> toList() { List<ElementType> result = new ArrayList<ElementType>(size()); for (ElementType e : this) result.add(e); return result; }
java
private static void loadRegistry() { // Load audit filters to runtime configurations. for (AuditEventFilter filter : PreConfigurationContext.getPrefilters()) { configContext.addFilter(filter); } // Load audit annotation filters to runtime configurations. for (AuditAnnotationFilter annotationFilter : PreCon...
python
def get_device_status(self, t): '''get device status at a given time t (within self.monitor_period)''' data = {} for name, (func, _, _) in self.addons.iteritems(): data[name] = func(t) return data
java
@Override public CPDefinitionSpecificationOptionValue findByC_CSOVI( long CPDefinitionId, long CPDefinitionSpecificationOptionValueId) throws NoSuchCPDefinitionSpecificationOptionValueException { CPDefinitionSpecificationOptionValue cpDefinitionSpecificationOptionValue = fetchByC_CSOVI(CPDefinitionId, CPD...
python
def default_matrix(self): """The default calibration matrix for this device. On most devices, this is the identity matrix. If the udev property ``LIBINPUT_CALIBRATION_MATRIX`` is set on the respective udev device, that property's value becomes the default matrix, see `Static device configuration via udev`_. ...
python
def addTags(self, tags): """Adds the list of tags to current tags. (flickr.photos.addtags) """ method = 'flickr.photos.addTags' if isinstance(tags, list): tags = uniq(tags) _dopost(method, auth=True, photo_id=self.id, tags=tags) #load properties again ...