language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public com.google.protobuf.ByteString getEnvironmentBytes() { java.lang.Object ref = environment_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); environment_ = b; re...
python
def cache_data(datatable, data, **kwargs): """ Stores the object list in the cache under the appropriate key. """ cache_key = '%s%s' % (CACHE_PREFIX, datatable.get_cache_key(**kwargs)) log.debug("Setting data to cache at %r: %r", cache_key, data) cache.set(cache_key, data)
java
public Observable<RouteFilterInner> createOrUpdateAsync(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).map(new Func1<ServiceResponse<RouteFilterInner>, RouteFilte...
python
def download_image(self, device_label, image_id, file_name): """ Download image taken by a smartcam Args: device_label (str): device label of camera image_id (str): image id from image series file_name (str): path to file """ response = None t...
python
def get_vowel(syll): '''Return the firstmost vowel in 'syll'.''' return re.search(r'([ieaouäöy]{1})', syll, flags=FLAGS).group(1).upper()
python
def readObject(self, innode): '''reads in a node and returns as a tuple: (type, name, points[])''' #get name names=innode.getElementsByTagName('name')[0].childNodes[0].data.strip() #get type pointType = 'Unknown' if len(innode.getElementsByTagName('LineString')) ...
java
public static MathModel createPolynom(int degree) { if (degree < 0) { throw new IllegalArgumentException("Degree must be positive"); } double[] params = new double[degree + 1]; params[0] = 1; StringBuilder format = new StringBuilder(); for (int i = degree; i >...
python
def random_hex(length): """ Return a random hex string. :param int length: The length of string to return :returns: A random string :rtype: str """ charset = ''.join(set(string.hexdigits.lower())) return random_string(length, charset)
python
def get_default_config(self): """ Returns the default collector settings """ config = super(IPCollector, self).get_default_config() config.update({ 'path': 'ip', 'allowed_names': 'InAddrErrors, InDelivers, InDiscards, ' + 'InHdrErrors, InReceives, InUn...
java
public ListAcceptedPortfolioSharesResult withPortfolioDetails(PortfolioDetail... portfolioDetails) { if (this.portfolioDetails == null) { setPortfolioDetails(new java.util.ArrayList<PortfolioDetail>(portfolioDetails.length)); } for (PortfolioDetail ele : portfolioDetails) { ...
python
def _check(peers): '''Checks whether the input is a valid list of peers and transforms domain names into IP Addresses''' if not isinstance(peers, list): return False for peer in peers: if not isinstance(peer, six.string_types): return False if not HAS_NETADDR: # if does ...
java
protected List<TypeVariableName> getTypeVariables(TypeName t) { return match(t) .when(typeOf(TypeVariableName.class)).get( v -> { if (v.bounds.isEmpty()) { return ImmutableList.of(v); } else { return Stream.concat( S...
java
public ApiResponse<ApiSuccessResponse> mediaStopMonitoringWithHttpInfo(String mediatype, MediaStopMonitoringData mediaStopMonitoringData) throws ApiException { com.squareup.okhttp.Call call = mediaStopMonitoringValidateBeforeCall(mediatype, mediaStopMonitoringData, null, null); Type localVarReturnType =...
python
def get(feature_name): """Returns the MetadataExtractor that can extract information about the provided feature name. Raises: UnsupportedFeature: If no extractor exists for the feature name. """ implementations = MetadataExtractor._implementations() try: ...
python
def get_bin(self): """Gets the ``Bin`` at this node. return: (osid.resource.Bin) - the bin represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: mgr = get_provider_manager('RESOURCE', runtime=self._...
java
private void closeServerSocket() { getLogger().debug("{} closing server socket", getName()); try { if (serverSocket != null) { serverSocket.close(); } } catch (Exception e) { // ignore for now } serverSocket = null; }
java
public void init(int iCheckCount, boolean bCheckedIsOn) { m_bCheckedIsOn = bCheckedIsOn; this.setBorder(null); this.setOpaque(false); this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); for (int i = 0; i < iCheckCount; i++) { JCheckBox checkBo...
java
private void preDelete(UserProfile userProfile, boolean broadcast) throws Exception { for (UserProfileEventListener listener : listeners) { listener.preDelete(userProfile); } }
java
public <T> void setDefaultValue(Class<T> type, T defaultValue) { Assert.notNull(type, "Class type is required"); this.defaultValues.put(type, defaultValue); }
python
def handle_exists(self, spec, checkable): '''The implementation of this one is weird. By the time the {'$exists': True} spec gets to the dispatched handler, the key presumably exists. So we just parrot the assertion the spec makes. If it asserts the key exists, we return True. I...
java
public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) { MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); for (Entry<String, Object> param : formParams.entrySet()) { if (param.getValue() instanceof File) { File file = (Fil...
python
def merge(cls, tables, fillna=False): """Merge a list of tables""" cols = set(itertools.chain(*[table.dtype.descr for table in tables])) tables_to_merge = [] for table in tables: missing_cols = cols - set(table.dtype.descr) if missing_cols: if fi...
python
def cut_cross(self, x, y, radius, data): """Cut two data subarrays that have a center at (x, y) and with radius (radius) from (data). Returns the starting pixel (x0, y0) of each cut and the respective arrays (xarr, yarr). """ n = int(round(radius)) ht, wd = data.shape ...
python
def getHostCertPath(self, name): ''' Gets the path to a host certificate. Args: name (str): The name of the host keypair. Examples: Get the path to the host certificate for the host "myhost": mypath = cdir.getHostCertPath('myhost') Retu...
python
def parse_args(): """Parse the arguments.""" parser = argparse.ArgumentParser( description='Show available clusters.' ) parser.add_argument( '-v', '--version', action='version', version="%(prog)s {0}".format(__version__), ) parser.add_argument( '--...
python
def render(self, template_name, **kw): ''' Given a template name and template vars. Searches a template file based on engine set, and renders it with corresponding engine. Returns a string. ''' logger.debug('Rendering template "%s"', template_name) vars =...
python
def upgrade(cfg): """Provide forward migration for configuration files.""" db_node = cfg["db"] old_db_elems = ["host", "name", "port", "pass", "user", "dialect"] has_old_db_elems = [x in db_node for x in old_db_elems] if any(has_old_db_elems): print("Old database configuration found. " ...
java
private List<String> getCollection(String value) { String arrayString = value; if (arrayString.startsWith("[") && arrayString.endsWith("]")) { arrayString = arrayString.substring(1, arrayString.length()-1); } return Arrays.stream(StringUtils.commaDelimitedListToStringArray(...
python
def cspace_convert(arr, start, end): """Converts the colors in ``arr`` from colorspace ``start`` to colorspace ``end``. :param arr: An array-like of colors. :param start, end: Any supported colorspace specifiers. See :ref:`supported-colorspaces` for details. """ converter = cspace_conv...
java
@Override public void messageReceived(IoSession session, Object message) throws Exception { log.debug("{} <-- {}", session, message); if (this.sensorIoAdapter == null) { log.warn( "No SensorIoAdapter defined. Ignoring message from {}: {}", session, message); return; } if (message instanceof...
python
def eval(e, amplitude, e_0, alpha, e_cutoff, beta): """One dimensional power law with an exponential cutoff model function """ xx = e / e_0 return amplitude * xx ** (-alpha) * np.exp(-(e / e_cutoff) ** beta)
python
def describe_events(ApplicationName=None, VersionLabel=None, TemplateName=None, EnvironmentId=None, EnvironmentName=None, PlatformArn=None, RequestId=None, Severity=None, StartTime=None, EndTime=None, MaxRecords=None, NextToken=None): """ Returns list of event descriptions matching criteria up to the last 6 wee...
python
def getAnalysisRequests(self, **kwargs): """Return all the Analysis Requests objects linked to the Batch kargs are passed directly to the catalog. """ brains = self.getAnalysisRequestsBrains(**kwargs) return [b.getObject() for b in brains]
java
public static int count(int[] array, int value) { int count = 0; for (int i = 0; i < array.length; i++) { if (array[i] == value) { count++; } } return count; }
java
@Override public <T> List<T> remove(Collection<? extends T> batchToRemove, String collectionName) { if (null == batchToRemove) { throw new InvalidJsonDbApiUsageException("Null Object batch cannot be removed from DB"); } CollectionMetaData cmd = cmdMap.get(collectionName); cmd.getCollectionLock()...
python
def get_metrics(awsclient, name): """Print out cloudformation metrics for a lambda function. :param awsclient :param name: name of the lambda function :return: exit_code """ metrics = ['Duration', 'Errors', 'Invocations', 'Throttles'] client_cw = awsclient.get_client('cloudwatch') for m...
python
def tree(self, subject_ids=None, visit_ids=None, **kwargs): """ Return the tree of subject and sessions information within a project in the XNAT repository Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. I...
java
@SuppressWarnings("rawtypes") public static <T extends Comparable> Collector<T, ?, List<T>> maxAll(final boolean areAllLargestSame) { return maxAll(Integer.MAX_VALUE, areAllLargestSame); }
java
public void error(String message, Object... args) { if (!NONE.equals(this.logLevel)) { System.out.println(String.format(message, args)); } }
python
def meta_wrapped(f): """ Add a field label, errors, and a description (if it exists) to a field. """ @wraps(f) def wrapped(self, field, *args, **kwargs): html = "{label}{errors}{original}<small>{description}</small>".format( label=field.label(class_='control-label'), ...
python
def process_repeated_list(self, key, lst, level): """ Process blocks of repeated keys e.g. FORMATOPTION """ lines = [] for v in lst: k = key.upper() v = self.quoter.add_quotes(v) lines.append(self.__format_line(self.whitespace(level, 1), k, v)...
java
public static void equalizeLocalRow( GrayU16 input , int radius , int startY , GrayU16 output , IWorkArrays workArrays ) { int width = 2*radius+1; int area = width*width; int maxValue = workArrays.length()-1; int[] histogram = workArrays.pop(); int[] transform = workArrays.pop(); // specify the...
python
def plot_envelope(M, C, mesh): """ plot_envelope(M,C,mesh) plots the pointwise mean +/- sd envelope defined by M and C along their base mesh. :Arguments: - `M`: A Gaussian process mean. - `C`: A Gaussian process covariance - `mesh`: The mesh on which to evaluate ...
java
public boolean contains(String name) { if (name == null) { throw new IllegalArgumentException("Other cannot be null"); } if (this.name.equals(name)) { return true; } if (hasReferences()) { for (Marker ref : referenceList) { ...
java
private void parseProperties(Element element, BeanDefinitionBuilder builder, ManagedList<AbstractBeanDefinition> propertyList) { NodeList properties = element.getChildNodes(); for (int i = 0; i < properties.getLength(); i++) { Node node = properties.item(i);...
java
public void setAgentHealthCodes(java.util.Collection<String> agentHealthCodes) { if (agentHealthCodes == null) { this.agentHealthCodes = null; return; } this.agentHealthCodes = new java.util.ArrayList<String>(agentHealthCodes); }
python
def submit_snl(self, snl): """ Submits a list of StructureNL to the Materials Project site. .. note:: As of now, this MP REST feature is open only to a select group of users. Opening up submissions to all users is being planned for the future. Args:...
python
def calcMassFromMz(mz, charge): """Calculate the mass of a peptide from its mz and charge. :param mz: float, mass to charge ratio (Dalton / charge) :param charge: int, charge state :returns: non protonated mass (charge = 0) """ mass = (mz - maspy.constants.atomicMassProton) * charge return...
python
def _send_request_to_node(self, node_id, request): """Send a Kafka protocol message to a specific broker. Will block until the message result is received. :param node_id: The broker id to which to send the message. :param request: The message to send. :return: The Kafka protoco...
python
def update_version(self, version: Union[http.HttpVersion, str]) -> None: """Convert request version to two elements tuple. parser HTTP version '1.1' => (1, 1) """ if isinstance(version, str): v = [l.strip() for l in version.split('.', 1)] try: ver...
python
def get_scan_log_lines(self, source_id, scan_id): """ Get the log text for a Scan :rtype: Iterator over log lines. """ return self.client.get_manager(Scan).get_log_lines(source_id=source_id, scan_id=scan_id)
java
public static ArrayList<Parser<?>> parsersFromSpecs(String[] specs) throws IllegalArgumentException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, IOException { final ArrayList<Parser<?>> parsers = new ArrayList<>(); for(final String spec :...
python
def cctop_save_xml(jobid, outpath): """Save the CCTOP results file in XML format. Args: jobid (str): Job ID obtained when job was submitted outpath (str): Path to output filename Returns: str: Path to output filename """ status = cctop_check_status(jobid=jobid) if stat...
java
@Override public PutRecordsResult putRecords(PutRecordsRequest request) { request = beforeClientExecution(request); return executePutRecords(request); }
java
public long cleanUpAllAllocatedMemory() { synchronized (this) { for (MemoryConsumer c: consumers) { if (c != null && c.getUsed() > 0) { // In case of failed task, it's normal to see leaked memory logger.debug("unreleased " + Utils.bytesToString(c.getUsed()) + " memory from " + c); ...
java
public synchronized Token put(Object key, Token value, Transaction transaction) throws ObjectManagerException { return put(key, value, transaction, false); }
python
def cable_from_file(filename): """\ Returns a cable from the provided file. `filename` An absolute path to the cable file. """ html = codecs.open(filename, 'rb', 'utf-8').read() return cable_from_html(html, reader.reference_id_from_filename(filename))
python
def C_array2dict(C): """Convert a 1D array containing C values to a dictionary.""" d = OrderedDict() i=0 for k in C_keys: s = C_keys_shape[k] if s == 1: j = i+1 d[k] = C[i] else: j = i \ + reduce(operator.mul, s, 1) d[k] = C[i...
java
@SuppressWarnings("unchecked") <T> T loadPlugin(final Class<T> pluginType) { return (T) loadPlugin(pluginType, null); }
python
def _directory (self): """The directory for this AitConfig.""" if self._filename is None: return os.path.join(self._ROOT_DIR, 'config') else: return os.path.dirname(self._filename)
python
def contents(self): """The raw file contents as a string.""" if not self._contents: if self._path: # Read file into memory so we don't run out of file descriptors f = open(self._path, "rb") self._contents = f.read() f.close() ...
python
def resolve_aonly(self,tables_dict,table_ctor): "circular depends on pgmock.Table. refactor." for alias,selectx in self.aonly.items(): table = table_ctor(alias,infer_columns(selectx,tables_dict),None) table.rows = run_select(selectx,tables_dict,table_ctor) self.aonly[alias] = table self.ao...
python
def read_byte_data(self, i2c_addr, register, force=None): """ Read a single byte from a designated register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Register to read :type register: int :param force: :type force: Boolean ...
java
@Override public ConsumerManager getLocalPtoPConsumerManager() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getLocalPtoPConsumerManager"); ConsumerManager consumerManager = _targetDestinationHandler.getLocalPtoPConsumerManager(); if (T...
python
def split_in_slices(number, num_slices): """ :param number: a positive number to split in slices :param num_slices: the number of slices to return (at most) :returns: a list of slices >>> split_in_slices(4, 2) [slice(0, 2, None), slice(2, 4, None)] >>> split_in_slices(5, 1) [slice(0, 5,...
python
def get_keys(logger=None, host_pkey_directories=None, allow_agent=False): """ Load public keys from any available SSH agent or local .ssh directory. Arguments: logger (Optional[logging.Logger]) host_pkey_directories (Optional[list[str]]): List of...
java
protected void renderDataCellContents(AbstractRenderAppender appender, String jspFragmentOutput) { assert DECORATOR != null; assert appender != null; assert _imageAnchorCellModel != null; String script = null; /* render any JavaScript needed to support framework features */ ...
java
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { currentAttributes = attributes; currentText = new StringBuilder(); if (SUPPRESS.equals(qName)) { rule = new SuppressionRule(); final String base...
python
def get_network_events(self): """ :calls: `GET /networks/:owner/:repo/events <http://developer.github.com/v3/activity/events>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Event.Event` """ return github.PaginatedList.PaginatedList( github.Eve...
python
def bundle_details(self, io_handler, bundle_id): """ Prints the details of the bundle with the given ID or name """ bundle = None try: # Convert the given ID into an integer bundle_id = int(bundle_id) except ValueError: # Not an intege...
java
public static Date parseDateStrictly(String str, String... parsePatterns) throws ParseException { return parseDateWithLeniency(str, null, parsePatterns, false); }
java
@Override public Iterator<String> iterator() { Iterator<String> it = new Iterator<String>() { private boolean isFirst = true; @Override public boolean hasNext() { return isFirst && !isEmpty(); } @Override public Str...
python
def get_figure_window_geometry(fig='gcf'): """ This will currently only work for Qt4Agg and WXAgg backends. Returns position, size postion = [x, y] size = [width, height] fig can be 'gcf', a number, or a figure object. """ if type(fig)==str: fig = _pylab.gcf() elif _fu...
python
def _get_grouped_dicoms(dicom_input): """ Search all dicoms in the dicom directory, sort and validate them fast_read = True will only read the headers not the data """ # if all dicoms have an instance number try sorting by instance number else by position if [d for d in dicom_input if 'Instance...
python
def cloud_train(train_dataset, eval_dataset, analysis_dir, output_dir, features, model_type, max_steps, num_epochs, train_batch_size, eval_batch_size, min_eval_...
java
protected SubscriptionSummary postNotification(final Subscriber subscriber, final String mimeType, final byte[] payload) { final SubscriptionSummary result = new SubscriptionSummary(); try { final URL target = new URL(subscriber.getCallback()); LOG.info("Posting notification to ...
python
def iterate_dict(container, exclude=None, path=None): """Iterate over a nested dictionary. The dictionary is iterated over in a depth first manner. :param container: Dictionary to iterate over :param exclude: Optional callable, which is given key and value as arguments and may return True to s...
java
private boolean hasSubject(String subject) { boolean result = false; String s = subject + "."; int c = s.length(); for (String propName : contextItems.getItemNames()) { result = s.equalsIgnoreCase(propName.substring(0, c)); if (result) { break; ...
java
@Override public String getAuditText() { return String.format("id = %s, req = %s(%s)", getId(), getMethodName(), PresentationUtils.toDisplayableString(getParams())); }
python
def multi_select(self, elements_to_select): """ Multi-select any number of elements. :param elements_to_select: list of WebElement instances :return: None """ # Click the first element first_element = elements_to_select.pop() self.click(first_element) ...
python
def clear(self): """Clears this instance's cache.""" if self._cache is not None: with self._cache as c: c.clear() c.out_deque.clear()
python
def format_tree(tree, root=None): ''' Tree pretty printer. Expects trees to be given as mappings (dictionaries). Keys will be printed; values will be traversed if they are mappings. To preserve order, use collections.OrderedDict. Example: print format_tree(collections.OrderedDict({'foo': 0, 'b...
java
@Nonnull public static <T> MockSupplier create (@Nonnull final Class <T> aDstClass, @Nonnull final Param [] aParams, @Nonnull final Function <IGetterDirectTrait [], T> aSupplier) { ValueEnforcer.notNull (aDstClass, "DstC...
java
public IStack<Object> tierOneUp(boolean newStack) { ++tier; IStack<Object> result; if (newStack || tierStack.size() == tier) { if (logging) { result = new LogStack<>(new ProcessStack<>(), System.out); } else { result = new ProcessStack<>(); } tierStack.add(result); } else { result = getTi...
python
def _setup_reference_files(data, tx_out_dir): """Create a reference directory with fasta and bwa indices. GRIDSS requires all files in a single directory, so setup with symlinks. This needs bwa aligner indices available, which we ensure with `get_aligner_with_aliases` during YAML sample setup. """ ...
java
private ExoContainer getContainer() throws ResourceException { ExoContainer container = ExoContainerContext.getCurrentContainer(); if (container instanceof RootContainer) { String portalContainerName = portalContainer == null ? PortalContainer.DEFAULT_PORTAL_CONTAINER_NAME : po...
python
def get_seconds(value, scale): """Convert time scale dict to seconds Given a dictionary with keys for scale and value, convert value into seconds based on scale. """ scales = { 'seconds': lambda x: x, 'minutes': lambda x: x * 60, 'hours': lambda x: x * 60 * 60, 'days': lambda x: x * 60 * 60 *...
java
public void showOver(Node target) { requireNonNull(target, "Parameter 'target' is null"); final Point2D center = center(target.localToScreen(target.getBoundsInLocal())); internalShow(target, target, center.getX(), center.getY()); }
java
@Override public CommerceOrderNote fetchByPrimaryKey(Serializable primaryKey) { Serializable serializable = entityCache.getResult(CommerceOrderNoteModelImpl.ENTITY_CACHE_ENABLED, CommerceOrderNoteImpl.class, primaryKey); if (serializable == nullModel) { return null; } CommerceOrderNote commerceOrderNo...
java
public static PathElement parseSingleKeyLHS( String origKey ) { String elementKey; // the String to use to actually make Elements String keyToInspect; // the String to use to determine which kind of Element to create if ( origKey.contains( "\\" ) ) { // only do the extra work of...
python
def df_to_parquet(df, filename, compression='SNAPPY'): """write_to_parquet: Converts a Pandas DataFrame into a Parquet file Args: df (pandas dataframe): The Pandas Dataframe to be saved as parquet file filename (string): The full path to the filename for the Parquet file """ ...
java
protected void fixClientID() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "fixClientID"); synchronized (stateLock) { clientIDFixed = true; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) ...
java
@Override public UpdateApplicationSettingsResult updateApplicationSettings(UpdateApplicationSettingsRequest request) { request = beforeClientExecution(request); return executeUpdateApplicationSettings(request); }
java
private static void formatBytesToSB (StringBuilder sb, byte[] data, int start, int countRequested, boolean displayCharRepresentations, int max) { if (max > MAX_TO_FORMAT) max = MAX_TO_FORMAT; // Ensure we can't be asked to format a completely bonkers amount of data int count = (countRequeste...
java
public static AsyncCallback<String> wrapCallback(final JavaScriptObject func) { return new AsyncCallback<String>() { public void onFailure(Throwable caught) { // TODO Auto-generated method stub } public void onSuccess(String result) { ...
java
private Object encodedPayload(Object payload) { LOG.debug("About to encode payload: {}", payload); if(payload == null || payload instanceof InputStream || payload.getClass() == byte[].class) { LOG.debug("Payload is null or binary - encoding skipped."); return payload; } ...
java
public WorkbookWriter turnToSheet(int index) { checkElementIndex(index, workbook.getNumberOfSheets()); sheet = workbook.getSheetAt(index); return this; }
java
@Override public DescribeInstanceAttributeResult describeInstanceAttribute(DescribeInstanceAttributeRequest request) { request = beforeClientExecution(request); return executeDescribeInstanceAttribute(request); }
java
public void cleanup() { ArrayList<ProducerReference> producerReferences = new ArrayList<ProducerReference>(registry.values()); for (ProducerReference p : producerReferences) { try { if (p.get() != null) unregisterProducer(p.get()); } catch (Exc...
python
def _import_astorb_to_database( self, astorbDictList): """*import the astorb orbital elements to database* **Key Arguments:** - ``astorbDictList`` -- the astorb database parsed as a list of dictionaries **Return:** - None """ self...