language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private String getBinaryPath() { String location = System.getProperty(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, Config.getConfigProperty(ConfigProperty.SELENIUM_PHANTOMJS_PATH)); return location; }
java
public static String getDuration(long diff) { GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(new Date(diff)); StringBuffer s = new StringBuffer(); if (calendar.get(Calendar.HOUR) > 1) { s.append("hours: " + (calendar.get(Calendar.HOUR) - 1) + ", "); ...
java
private static long deriveTokenInterval(ImmutableSortedSet<Integer> tokens) { long interval = 0; int count = 4; int prevToken = Integer.MIN_VALUE; UnmodifiableIterator<Integer> tokenIter = tokens.iterator(); while (tokenIter.hasNext() && count-- > 0) { int nextTok...
java
@Override public String getMimeType() { String contentType = backing.getContentType(); // IE6 (and apparently IE7) are broken and send the MIME type "image/pjpeg" // regardless of whether the image is a progressive jpeg or not. Sending the // incorrect MIME type back can cause display issues. It is always saf...
python
def add_metric(self, labels, value, timestamp=None): """Add a metric to the metric family. Args: labels: A list of label values value: A dict of labels """ self.samples.append(Sample( self.name + '_info', dict(dict(zip(self._labelnames, labels...
java
@Override synchronized public V put(K key, V value) { V oldValue = this.get(key); try { super.put(key, value); writeBack(key, value); return oldValue; } catch(Exception e) { super.put(key, oldValue); writeBack(key, oldValue); ...
java
public void marshall(PutConfigRuleRequest putConfigRuleRequest, ProtocolMarshaller protocolMarshaller) { if (putConfigRuleRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(putConfigRuleReques...
python
def __store_record(self, record): """ Save record in a internal storage :param record: record to save :return: None """ if isinstance(record, WSimpleTrackerStorage.Record) is False: raise TypeError('Invalid record type was') limit = self.record_limit() if limit is not None and len(self.__registry) >=...
java
public Criteria and(String key) { checkComplete(); return new Criteria(this.criteriaChain, ValueNode.toValueNode(prefixPath(key))); }
python
def lowest_cost_action(ic, dc, sc, im, dm, sm, cost): """Given the following values, choose the action (insertion, deletion, or substitution), that results in the lowest cost (ties are broken using the 'match' score). This is used within the dynamic programming algorithm. * ic - insertion cost * ...
python
def install(self, struct, ui, debug=False): """ This is the only method that should be called from outside. Call it like: `DependencyInstaller(struct)` and it will install packages which are not present on system (it uses package managers specified by `struct` structure) ...
java
public Blob copyBlobInChunks(String bucketName, String blobName, String copyBlobName) { // [START copyBlobInChunks] CopyRequest request = CopyRequest.newBuilder() .setSource(BlobId.of(bucketName, blobName)) .setTarget(BlobId.of(bucketName, copyBlobName)) .build(); ...
java
public boolean match(GregorianCalendar calendar, boolean isMatchSecond) { final int second = calendar.get(Calendar.SECOND); final int minute = calendar.get(Calendar.MINUTE); final int hour = calendar.get(Calendar.HOUR_OF_DAY); final int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); final int month = ...
python
def element_statistics(tree, element_type): """ Prints the names and counts of all elements present in an `etree._ElementTree`, e.g. a SaltDocument:: SStructure: 65 SSpan: 32 SToken: 154 STextualDS: 1 Parameters ---------- tree : lxml.etree._ElementTree ...
java
public FessMessages addSuccessCrudCreateCrudTable(String property) { assertPropertyNotNull(property); add(property, new UserMessage(SUCCESS_crud_create_crud_table)); return this; }
python
def route(self, uri, *args, **kwargs): """Create a plugin route from a decorated function. :param uri: endpoint at which the route will be accessible. :type uri: str :param args: captures all of the positional arguments passed in :type args: tuple(Any) :param kwargs: capt...
python
def _extrac_qtl(peak, block, headers): """ Given a row containing the peak of the QTL and all the rows of the linkage group of the said QTL (splitted per trait), determine the QTL interval and find the start and stop marker of the said interval. The interval is a LOD 2 interval. The approach is ...
java
public S setParameter(String key, String value) { if (parameters == null) { parameters = new ConcurrentHashMap<String, String>(); } if (value == null) { parameters.remove(key); } else { parameters.put(key, value); } return castThis(); ...
java
public static Method getterOrSetter(Class clazz, String fieldName, FieldAccessType methodType) throws IntrospectionException { if (null == fieldName || "".equals(fieldName)) return null; BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] props = b...
java
public void setRegularization(double regularization) { if (Double.isInfinite(regularization) || Double.isNaN(regularization) || regularization <= 0) throw new IllegalArgumentException("Regularization must be a positive value"); this.reg = regularization; }
java
public static String format(final String pattern, final Locale locale, final Object... arguments) { MessageFormat format = new MessageFormat(pattern, locale); return format.format(arguments); }
java
@Override protected void prepare(final AbstractSQLInsertUpdate<?> _insertUpdate, final Attribute _attribute, final Object... _values) throws SQLException { checkSQLColumnSize(_attribute, 2); final StringWithUoM value = eval(_values); ...
java
@ArgumentsChecked @Throws({ IllegalNullArgumentException.class, IllegalPatternArgumentException.class }) public static <T extends CharSequence> void matchesPattern(final boolean condition, @Nonnull final Pattern pattern, @Nonnull final T chars, @Nullable final String name) { if (condition) { Check.matchesPatt...
java
private String buildMediaUrl(Dimension scaledDimension) { // check for file extension filtering if (!isMatchingFileExtension()) { return null; } // check if image has to be rescaled if (scaledDimension != null) { // check if scaling is not possible if (scaledDimension.equals(SCA...
java
@Nonnull @Nonempty @Deprecated public static String getFieldName (@Nonnull @Nonempty final String sBaseName) { ValueEnforcer.notEmpty (sBaseName, "BaseName"); return sBaseName; }
python
def print_rackspace_info(region, instance_id, access_key_id, secret_access_key, username): """ outputs information about our Rackspace instance """ data = get_rackspace_info(server_id=instance_id, ...
java
public Vector4f transform(Vector4fc vec, Vector4f dest) { return transform(vec.x(), vec.y(), vec.z(), dest); }
java
@SuppressWarnings("unchecked") public List<Class<Object>> getItems(final Predicate<ItemInfo> filter) { final List<Class<Object>> items = (List) Lists.newArrayList(itemsHolder.values()); return filter(items, filter); }
python
def function_nodes(self): """ Returns all function nodes of the dispatcher. :return: All data function of the dispatcher. :rtype: dict[str, dict] """ return {k: v for k, v in self.nodes.items() if v['type'] == 'function'}
python
def execute(self, program, start=None, stop=None, resolution=None, max_delay=None, persistent=False, immediate=False, disable_all_metric_publishes=None): """Execute the given SignalFlow program and stream the output back.""" params = self._get_params(start=start, stop=sto...
java
private void processEntry(ManifestEntryVerifier mev) throws IOException { if (!parsingBlockOrSF) { JarEntry je = mev.getEntry(); if ((je != null) && (je.signers == null)) { je.signers = mev.verify(verifiedSigners, sigFileSigners); je.certs = ma...
java
public static Object[] boxAll(Class<?> type, Object src, int srcPos, int len) { switch (tId(type)) { case I_BOOLEAN: return boxBooleans(src, srcPos, len); case I_BYTE: return boxBytes(src, srcPos, len); case I_CHARACTER: return boxCharacters(src, srcPos, len); ...
python
def unicode(self, var, default=NOTSET): """Helper for python2 :rtype: unicode """ return self.get_value(var, cast=str, default=default)
python
def timeshift(self): """Return if the stream is a timeshift.""" if self.tune and self.tune.get('@src'): return True if self.tune.get('@src').startswith('timeshift') else False else: raise PyMediaroomError("No information in <node> about @src")
python
def jwt_get_secret_key(payload=None): """ For enchanced security you may use secret key on user itself. This way you have an option to logout only this user if: - token is compromised - password is changed - etc. """ User = get_user_model() # noqa if api_settings.JWT_GET...
java
@TargetApi(Build.VERSION_CODES.GINGERBREAD) public static boolean hasGyroscopeSensorFeature(PackageManager manager) { return manager.hasSystemFeature(PackageManager.FEATURE_SENSOR_GYROSCOPE); }
python
def clear_all(): """ Clears all parameters, variables, and shocks defined previously """ frame = inspect.currentframe().f_back try: if frame.f_globals.get('variables_order'): # we should avoid to declare symbols twice ! del frame.f_globals['variables_order'] ...
python
def client_getter(): """Decorator to retrieve Client object and check user permission.""" def wrapper(f): @wraps(f) def decorated(*args, **kwargs): if 'client_id' not in kwargs: abort(500) client = Client.query.filter_by( client_id=kwargs....
java
public final boolean isDayChange() { if (!getEventType().equals(ENTRY_INTERVAL_CHANGED)) { return false; } Interval newInterval = entry.getInterval(); Interval oldInterval = getOldInterval(); ZonedDateTime newStart = newInterval.getStartZonedDateTime(); Zone...
python
def disable_hostgroup_host_notifications(self, hostgroup): """Disable host notifications for a hostgroup Format of the line that triggers function call:: DISABLE_HOSTGROUP_HOST_NOTIFICATIONS;<hostgroup_name> :param hostgroup: hostgroup to disable :type hostgroup: alignak.object...
java
public static boolean containsFile(final File fileToSearch, final String pathname) { final String[] allFiles = fileToSearch.list(); if (allFiles == null) { return false; } final List<String> list = Arrays.asList(allFiles); return list.contains(pathname); }
java
private void processOsRegex(String useragent, UserAgentInfo retObj) { try { lock.lock(); for (Map.Entry<Pattern, Long> entry : osRegMap.entrySet()) { Matcher matcher = entry.getKey().matcher(useragent); if (matcher.find()) { // simply ...
java
private static String getHeaderInfo(String name, String headerLine) { String[] fields = headerLine.split("[\t ]"); for (String field : fields) { if (field.startsWith(name + "=")) { String[] subfields = field.split("="); return subfields[1]; } ...
python
def enable_svc_event_handler(self, service): """Enable event handlers for a service Format of the line that triggers function call:: ENABLE_SVC_EVENT_HANDLER;<host_name>;<service_description> :param service: service to edit :type service: alignak.objects.service.Service ...
java
private static int compareLobContents(final IonLob lob1, final IonLob lob2) { int in1 = lob1.byteSize(); int in2 = lob2.byteSize(); int result = (in1- in2); if (result == 0) { final InputStream stream1 = lob1.newInputStream(); final InputStream stream2 = lob2...
java
private int nextSetBit(int fromIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); int u = intIndex(fromIndex); int arrayLength = array.length(); if (u >= arrayLength) return -1; int possible = array.get(u) & (INT_MASK << from...
java
public List<LicenseTemplate> getAllLicenseTemplates() throws GitLabApiException { Response response = get(Response.Status.OK, null, "licenses"); return (response.readEntity(new GenericType<List<LicenseTemplate>>() {})); }
java
public TempBlockMeta createTempBlockMeta(long sessionId, long blockId, long initialBlockSize) { return new TempBlockMeta(sessionId, blockId, initialBlockSize, mDir); }
python
def check_deps(deps): """check whether specific requirements are available.""" if not isinstance(deps, list): deps = [deps] checks = list(Environment.has_apps(deps)) if not all(checks): for name, available in list(dict(zip(deps, checks)).items()): ...
java
@Override public void writeEnvelope(RecordEnvelope<D> record) throws IOException { try { if (ThrottleType.QPS.equals(type)) { acquirePermits(1L); } long beforeWrittenBytes = writer.bytesWritten(); writer.writeEnvelope(record); if (ThrottleType.Bytes.equals(type)) { l...
python
def remove_model_prefix(self, id): '''remove_model_prefix High-level api: If prefix is the model prefix, return tagname without prefix. If prefix is not the model prefix, simply return the identifier without modification. Parameters ---------- id : `str` ...
python
def averages(self): """ Access to the average of the values at the vertices for each triangle. If the quantities are defined at centers instead of vertices, this will return None. Also see :method:`centers`. :return: numpy array or None """ if not self.mesh._com...
java
private final void resizeClean() { //must resize, but are we at tgt size? final int lgTgtLongs = lgNomLongs_ + 1; if (lgTgtLongs > lgArrLongs_) { //not yet at tgt size final ResizeFactor rf = getResizeFactor(); final int lgDeltaLongs = lgTgtLongs - lgArrLongs_; //must be > 0 final in...
python
def xyz2rgb(x__, y__, z__): """XYZ colorspace to RGB """ x2_ = x__ / 100.0 y2_ = y__ / 100.0 z2_ = z__ / 100.0 r__ = x2_ * 3.2406 + y2_ * -1.5372 + z2_ * -0.4986 g__ = x2_ * -0.9689 + y2_ * 1.8758 + z2_ * 0.0415 b__ = x2_ * 0.0557 + y2_ * -0.2040 + z2_ * 1.0570 def finv(arr): ...
python
def mkApplications(location, *atoms): """Make a sequence of applications from a list of tokens. atoms is a list of atoms, which will be handled left-associatively. E.g: ['foo', [], []] == foo()() ==> Application(Application('foo', []), []) """ atoms = list(atoms) while len(atoms) > 1: atoms[0:2] =...
java
protected StreamContext getStreamContext() { StreamContext context = new StreamContext(); solrClientCache = new SparkSolrClientCache(cloudSolrClient, httpSolrClient); context.setSolrClientCache(solrClientCache); context.numWorkers = numWorkers; context.workerID = workerId; return context; }
java
void createStructure() throws RepositoryException { Session session = getStorageSession(); try { Node storage = session.getRootNode().addNode(storagePath.substring(1), STORAGE_NODETYPE); storage.addNode(STORAGE_JOS_USERS, STORAGE_JOS_USERS_NODETYPE); storage.addNode(STOR...
python
def pretty_format_table(labels, data, num_format="{:.3f}", line_separator="\n"): """Parses and creates pretty table :param labels: List of labels of data :param data: Matrix of any type :param num_format: Format numbers with this format :param line_separator: Separate each new line with this :r...
python
def split_filename(filename, project_name=None): """ Extract name, version, python version from a filename (no extension) Return name, version, pyver or None """ result = None pyver = None filename = unquote(filename).replace(' ', '-') m = PYTHON_VERSION.search(filename) if m: ...
python
def setParameter(self, parameterName, index, parameterValue): """ Set the value of a Spec parameter. """ spec = self.getSpec() if parameterName not in spec['parameters']: raise Exception("Unknown parameter: " + parameterName) setattr(self, parameterName, parameterValue)
python
def report_fooof(self, x, y, suffix): """Create FOOOF (fitting oscillations and 1/f) report. Parameters ---------- x : ndarray vector with frequencies y : ndarray vector with amplitudes """ filename = splitext(self.filename)[0] + '_' + suf...
java
@Override public ConversationReceiveListener dataReceived(WsByteBuffer data, int segmentType, int requestNumber, int priority, boolean allocatedFromBufferPool, ...
java
private static void finalClose(final Closeable closeMe) { if (closeMe != null) { try { closeMe.close(); } catch (IOException iox) { LOG.log(Level.FINEST, "Could not close: " + closeMe, iox); } } }
python
def subnets_list(virtual_network, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 List all subnets within a virtual network. :param virtual_network: The virtual network name to list subnets within. :param resource_group: The resource group name assigned to the virtual network. ...
java
private CmsTreeItem buildTreeItem(CmsCategoryTreeEntry category, Collection<String> selectedCategories) { // generate the widget that should be shown in the list CmsDataValue dataValue = new CmsDataValue( 600, 3, CmsCategoryBean.SMALL_ICON_CLASSES, ...
python
def helical_turbulent_fd_Prasad(Re, Di, Dc,roughness=0): r'''Calculates Darcy friction factor for a fluid flowing inside a curved pipe such as a helical coil under turbulent conditions, using the method of Prasad [1]_, also shown in [2]_. .. math:: f_{curv} = f_{\text{str,turb}}\left[...
java
public static Money min(Money money1, Money money2) { if (money1 == null) { return money2; } if (money2 == null) { return money1; } return money1.compareTo(money2) < 0 ? money1 : money2; }
java
public static void hideSoftKeyboard(@NonNull Context context, @Nullable View focusedView) { if (focusedView == null) { return; } final InputMethodManager manager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); manager.hideSoftI...
java
@SuppressWarnings("unchecked") @Override public EList<String> getDirectionRatiosAsString() { return (EList<String>) eGet(Ifc4Package.Literals.IFC_DIRECTION__DIRECTION_RATIOS_AS_STRING, true); }
java
@Override public Object invoke(MethodInvocation invocation) throws Throwable { // cette méthode est appelée par spring aop if (DISABLED || !SPRING_COUNTER.isDisplayed()) { return invocation.proceed(); } // nom identifiant la requête final String requestName = getRequestName(invocation); boolea...
java
public void setEditMode(final EditMode mode) { if (!m_modeSelect.getValue().equals(mode)) { m_modeSelect.setValue(mode); } }
python
def _imported_symbol(import_path): """Resolve a dotted path into a symbol, and return that. For example... >>> _imported_symbol('django.db.models.Model') <class 'django.db.models.base.Model'> Raise ImportError if there's no such module, AttributeError if no such symbol. """ module_na...
python
def _is_playlist_in_config_dir(self): """ Check if a csv file is in the config dir """ if path.dirname(self.stations_file) == self.stations_dir: self.foreign_file = False self.foreign_filename_only_no_extension = '' else: self.foreign_file = True s...
java
static BundleFile installBundle(Config config, Resource resJar, String extVersion, boolean convert2bundle) throws IOException, BundleException { BundleFile bf = new BundleFile(resJar); // resJar is a bundle if (bf.isBundle()) { return installBundle(config, bf); } if (!convert2bundle) return null; // name...
java
@Action( semantics = SemanticsOf.SAFE ) @MemberOrder(sequence = "3") public List<Gmap3ToDoItem> complete() { final List<Gmap3ToDoItem> items = completeNoUi(); if(items.isEmpty()) { messageService.informUser("No to-do items have yet been completed :-("); } ...
python
def get_client_properties_per_page(self, per_page=1000, page=1, params=None): """ Get client properties per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list ...
java
public void marshall(PortProbeAction portProbeAction, ProtocolMarshaller protocolMarshaller) { if (portProbeAction == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(portProbeAction.getBlocked(), BLOC...
java
public static JPanel makeButtonBox (Justification justification, Component... buttons) { JPanel box = new JPanel(new HGroupLayout(NONE, justification)); for (Component button : buttons) { box.add(button); box.setOpaque(false); } return box; }
java
@Override public void cancelTimeouts(final String sagaId) { checkNotNull(sagaId, "SagaId parameter must not be null."); synchronized (sync) { Collection<TimeoutId> timeoutsToRemove = new ArrayList<>(); Map<TimeoutId, ScheduledFuture> sagaTimeouts = openTimeouts.column(sagaId...
java
public static <T> SNAXParser<T> createParser(XMLInputFactory factory, NodeModel<T> model) { return new SNAXParser<T>(factory, model); }
python
def setDelta(self, delta): """ Sets the time delta for this widget to the inputed delta. :param delta | <datetime.timedelta> """ days = int(delta.days) secs = int(delta.total_seconds()) direction = 'from now' if secs < 0: ...
java
@Override public XBELAnnotationGroup convert(AnnotationGroup source) { if (source == null) return null; List<Annotation> annotations = source.getAnnotations(); Citation citation = source.getCitation(); Evidence evidence = source.getEvidence(); XBELAnnotationGroup xag = new ...
java
private void fail(BeanError error) { Log.e(TAG, "OAD Error: " + error.toString()); if (uploadInProgress()) { oadListener.error(error); reset(); } }
java
public static String startWithSpace(String value) { if (value.length() > 0 && (value.charAt(0) != ' ' && value.charAt(0) != '\t')) { return " " + value; } return value; }
java
private File getKeenCacheDirectory() throws IOException { File file = new File(root, "keen"); if (!file.exists()) { boolean dirMade = file.mkdir(); if (!dirMade) { throw new IOException("Could not make keen cache directory at: " + file.getAbsolutePath()); ...
java
static String readString(final InputStream is) { try (final Scanner s = new Scanner(is, "UTF-8")) { s.useDelimiter("\\A"); if (s.hasNext()) { return s.next(); } else { return ""; } } }
python
def to_yaml(obj): """ This function returns correct YAML representation of a UAVCAN structure (message, request, or response), or a DSDL entity (array or primitive), or a UAVCAN transfer, with comments for human benefit. Args: obj: Object to convert. Returns: Unicode string conta...
python
def suspend_to_background(self, suspend_group=True): """ (Not thread safe -- to be called from inside the key bindings.) Suspend process. :param suspend_group: When true, suspend the whole process group. (This is the default, and probably what you want.) """ ...
java
VariableMap getPropertyMap() { ImmutableMap.Builder<String, String> map = ImmutableMap.builder(); for (Property p : propertyMap.values()) { if (p.newName != null) { map.put(p.oldName, p.newName); } } return new VariableMap(map.build()); }
python
def recall_score(df, col_true=None, col_pred='precision_result', pos_label=1, average=None): r""" Compute recall of a predicted DataFrame. Precision is defined as :math:`\frac{TP}{TP + FP}` :Parameters: - **df* - predicted data frame - **col_true** - column name of true label - **co...
python
def create_fwrule(kwargs=None, call=None): ''' Create a GCE firewall rule. The 'default' network is used if not specified. CLI Example: .. code-block:: bash salt-cloud -f create_fwrule gce name=allow-http allow=tcp:80 ''' if call != 'function': raise SaltCloudSystemExit( ...
python
def get_source(self, environment, template): """.. seealso:: :meth:`jinja2.loaders.FileSystemLoader.get_source` """ pieces = jinja2.loaders.split_template_path(template) for searchpath in self.searchpath: filename = os.path.join(searchpath, *pieces) if self.enable...
python
def device_function(self, var): """Choose a device for the input variable. Args: var: an Variable. Returns: The device for placing the var. """ if var.type not in ('Variable', 'VariableV2', 'VarHandleOp'): tf.logging.debug('Place {} on last device: {}.'.format( var.name...
java
public void setOption(String optName, String optValue) { if (optValue == null) { m_optionMap.remove(optName); } else { m_optionMap.put(optName, optValue.trim()); } }
python
def get_netspeed(self, ip): ''' Get netspeed ''' rec = self.get_all(ip) return rec and rec.netspeed
python
def draw(obj, mode='2d', **kwargs): '''Draw a morphology object Parameters: obj: morphology object to be drawn (neuron, tree, soma). mode (Optional[str]): drawing mode ('2d', '3d', 'dendrogram'). Defaults to '2d'. **kwargs: keyword arguments for underlying neurom.view.view functions. ...
python
def start(self, device): """Start serving access to this VirtualIOTileDevice Args: device (VirtualIOTileDevice): The device we will be providing access to """ super(NativeBLEVirtualInterface, self).start(device) self.set_advertising(True)
java
public static void displayArray(int[] array) { String line = ""; for (int f = 0; f < array.length; f++) { line += array[f] + " | "; } logger.debug(line); }
python
def get_values(self): """ Applies parsing functions to each input as specified in init before returning a tuple with first entry being a boolean which specifies if the user entered all values and a second entry which is a dictionary of input names to parsed values. """ return_dict = {} ...
java
public static List<CDKRMap> getSubgraphMap(IAtomContainer sourceGraph, IAtomContainer targetGraph, boolean shouldMatchBonds) throws CDKException { List<CDKRMap> result = null; List<List<CDKRMap>> rMapsList = search(sourceGraph, targetGraph, new BitSet(), getBitSet(targetGraph), false, ...