language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected CmsAccessControlEntry internalCreateAce(ResultSet res) throws SQLException { return internalCreateAce(res, new CmsUUID(res.getString(m_sqlManager.readQuery("C_ACCESS_RESOURCE_ID_0")))); }
java
private Variable getVariableAtNode(int index, CallStack callstack) throws UtilEvalError { Node nameNode = null; if (jjtGetChild(index).jjtGetNumChildren() > 0 && (nameNode = jjtGetChild(index).jjtGetChild(0)) instanceof BSHAmbiguousName) return callstack.t...
python
def make_response(status, headers, payload, environ): """This function generates an appropriate response object for this async mode. """ return Response(body=payload, status=int(status.split()[0]), headers=headers)
java
@Override public int getShardId(final Object[] objs) { if (objs == null || objs.length == 0) { return 0; } Object input = null; if (objs[0] == null) { return 0; } if (objs[0] instanceof List) { List<?> list = (List<?>) objs[0]; ...
java
private static String getProperty(Properties extensionProperties, String propertyName) { if (extensionProperties.containsKey(propertyName)) { Object value = extensionProperties.get(propertyName); if (value != null) { return value.toString(); } } ...
python
def _check_not_hanging(self): """ Rough check that generate() will not hang or be very slow. Raises ConfigurationError if generate() spends too much time in retry loop. Issues a warning.warn() if there is a risk of slowdown. """ # (field_name, predicate, warning_msg, exc...
python
def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs): """ Deprecated see make_data_classif """ return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs)
python
def db_optimize(name, table=None, **connection_args): ''' Optimizes the full database or just a given table CLI Example: .. code-block:: bash salt '*' mysql.db_optimize dbname ''' ret = [] if table is None: # we need to optimize all tables ...
python
def command(self, details): """ Handles executing a command-based event. This starts the command as specified in the 'commands' section of the task config. A separate event is registered to handle the command exit. This simply logs the exit status. """ log = self._...
java
@Override public boolean isValid(TagData us) { if (!Util.isSpecified(us, ITEMS)) { if (!Util.isSpecified(us, BEGIN) || !(Util.isSpecified(us, END))) { return false; } } return true; }
python
def add_token(self, token): """Add token to vocabulary. Args: token (str): token to add. """ token = self.process_token(token) self._token_count.update([token])
java
public Class<? extends org.eclipse.xtext.parser.antlr.ITokenDefProvider> bindITokenDefProvider() { return org.eclipse.xtext.parser.antlr.AntlrTokenDefProvider.class; }
python
def get_resource_ids_by_bin(self, bin_id): """Gets the list of ``Resource`` ``Ids`` associated with a ``Bin``. arg: bin_id (osid.id.Id): ``Id`` of a ``Bin`` return: (osid.id.IdList) - list of related resource ``Ids`` raise: NotFound - ``bin_id`` is not found raise: NullArg...
python
def open(self, event): """Opens a file that is specified in event.attr Parameters ---------- event.attr: Dict \tkey filepath contains file path of file to be loaded \tkey filetype contains file type of file to be loaded \tFiletypes can be pys, pysu, xls ...
java
public boolean isInDiskCacheSync(final Uri uri, final ImageRequest.CacheChoice cacheChoice) { ImageRequest imageRequest = ImageRequestBuilder .newBuilderWithSource(uri) .setCacheChoice(cacheChoice) .build(); return isInDiskCacheSync(imageRequest); }
java
private void computeV( DMatrixRMaj h1 ,DMatrixRMaj h2 , DMatrixRMaj v ) { double h1x = h1.get(0,0); double h1y = h1.get(1,0); double h1z = h1.get(2,0); double h2x = h2.get(0,0); double h2y = h2.get(1,0); double h2z = h2.get(2,0); v.set(0,0,h1x*h2x); v.set(0,1,h1x*h2y+h1y*h2x); v.set(0,2,h1y*h2y); ...
python
def delete_collection_namespaced_persistent_volume_claim(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_persistent_volume_claim # noqa: E501 delete collection of PersistentVolumeClaim # noqa: E501 This method makes a synchronous HTTP request by default. To make an ...
python
def rc4(data, key): """RC4 encryption and decryption method.""" S, j, out = list(range(256)), 0, [] for i in range(256): j = (j + S[i] + ord(key[i % len(key)])) % 256 S[i], S[j] = S[j], S[i] i = j = 0 for ch in data: i = (i + 1) % 256 j = (j + S[i]) % 256 S[...
java
public Producer<CloseableReference<PooledByteBuffer>> getNetworkFetchEncodedImageProducerSequence() { synchronized (this) { if (FrescoSystrace.isTracing()) { FrescoSystrace.beginSection( "ProducerSequenceFactory#getNetworkFetchEncodedImageProducerSequence"); } if (mNetworkEnc...
python
def decode(self, text: str, prefix: str = "@") -> str: """Decode <@id> and <!alias> into @username.""" def callback(match: Match) -> str: m = match.groupdict() if m["userid"]: user = self.users.get(m["userid"], None) if user is None: ...
java
@Override public void visitCode(Code obj) { Method m = getMethod(); String sig = m.getSignature(); if (!Values.SIG_VOID.equals(SignatureUtils.getReturnSignature(sig))) { state = State.SEEN_NOTHING; branchTargets.clear(); CodeException[] ces = obj.getExcept...
python
def allowDeletion(store, tableClass, comparisonFactory): """ Returns a C{bool} indicating whether deletion of an item or items of a particular item type should be allowed to proceed. @param tableClass: An L{Item} subclass. @param comparison: A one-argument callable taking an attribute and retu...
python
def nphase_border(im, include_diagonals=False): r''' Identifies the voxels in regions that border *N* other regions. Useful for finding triple-phase boundaries. Parameters ---------- im : ND-array An ND image of the porous material containing discrete values in the pore space i...
java
public static <T, X extends Throwable> T throwThe(X e) throws X { if (e == null) { throw new ExceptionNotHandled("Cannot throw null exception."); } throw e; }
python
def _re_flatten(p): ''' Turn all capturing groups in a regular expression pattern into non-capturing groups. ''' if '(' not in p: return p return re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:', p)
python
def Serialize(self, writer): """ Serialize object. Args: writer (neo.IO.BinaryWriter): """ self.SerializeUnsigned(writer) writer.WriteSerializableArray(self.scripts)
python
def modify_subscription_status(netid, subscription_code, status): """ Post a subscription 'modify' action for the given netid and subscription_code """ url = _netid_subscription_url(netid, subscription_code) body = { 'action': 'modify', 'value': str(status) } response = ...
python
def get(cls, bucket, key, upload_id, with_completed=False): """Fetch a specific multipart object.""" q = cls.query.filter_by( upload_id=upload_id, bucket_id=as_bucket_id(bucket), key=key, ) if not with_completed: q = q.filter(cls.completed....
python
def _put_task_in_run_log(self, task_name): """ Initializes the run log task entry for this task. """ logger.debug('Job {0} initializing run log entry for task {1}'.format(self.name, task_name)) data = {'start_time': datetime.utcnow(), 'command': self.tasks[task_name].command} ...
java
public static SSLSocketFactory getPinnedCertSslSocketFactory(Context context, int keyStoreRawResId, String keyStorePassword) { InputStream in = null; try { // Get an instance of th...
java
public double getDouble(String attrName) { BigDecimal bd = getNumber(attrName); if (bd == null) throw new NumberFormatException ("value of " + attrName + " is null"); return bd.doubleValue(); }
java
public List<Class<?>> getClasses(final String pkg, boolean recursive, final Predicate<Class<?>> predicate) { final long started = System.currentTimeMillis(); try { return filter(finder.findClassesInPackage(pkg, recursive), predicate); } finally { final long finished = System.currentTimeMillis(); ...
python
def on_clear_button_pressed(self): """ PyQt slot called when the user hits the "Clear" button. Removes any set custom module search path. """ self.path = None self.clear_button.setEnabled(False) self.folder_label.setText(self.initial_folder_label_text) log...
java
public static Date parseToDate(final String date, final String format) throws ParseException { final DateFormat df = new SimpleDateFormat(format); Date parsedDate = null; parsedDate = df.parse(date); return parsedDate; }
java
public static EdgeRcClientCredentialProvider fromEdgeRc(File file, String section) throws ConfigurationException, IOException { Objects.requireNonNull(file, "file cannot be null"); return fromEdgeRc(new FileReader(file), section); }
python
def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs): """ Initializes a NEBAnalysis object from a directory of a NEB run. Note that OUTCARs must be present in all image directories. For the terminal OUTCARs from relaxation calculations, you can specify the locations using ...
java
public void restoreExistingRepository(RepositoryBackupChainLog rblog, RepositoryEntry repositoryEntry, boolean asynchronous) throws BackupOperationException, BackupConfigurationException { try { // repository should be existed repoService.getRepository(repositoryEntry.getName()); ...
python
def repodata_files(self, channels=None): """ Return the repodata paths based on `channels` and the `data_directory`. There is no check for validity here. """ if channels is None: channels = self.conda_get_condarc_channels() repodata_urls = self._set_repo_url...
java
public final Queue purgeQueue(String name) { PurgeQueueRequest request = PurgeQueueRequest.newBuilder().setName(name).build(); return purgeQueue(request); }
java
public FavoriteLogCB acceptPK(String id) { assertObjectNotNull("id", id); BsFavoriteLogCB cb = this; cb.query().docMeta().setId_Equal(id); return (FavoriteLogCB) this; }
java
public static List<String> extractParameters(String rawRoute) { List<String> list = new ArrayList<>(); Matcher m = PATH_PARAMETER_REGEX.matcher(rawRoute); while (m.find()) { if (m.group(1).indexOf('<') != -1) { // Regex case name<reg> list.add(m.grou...
java
private void skipPayload(int numBytes) throws IOException { while (true) { int bufferRemaining = buffer.size() - position; if (bufferRemaining >= numBytes) { position += numBytes; return; } else { pos...
java
public Observable<String> supportedVpnDevicesAsync(String resourceGroupName, String virtualNetworkGatewayName) { return supportedVpnDevicesWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).map(new Func1<ServiceResponse<String>, String>() { @Override public String cal...
python
def includeme(configurator): """ Add yaml configuration utilities. :param pyramid.config.Configurator configurator: pyramid's app configurator """ settings = configurator.registry.settings # lets default it to running path yaml_locations = settings.get('yaml.location', ...
java
public void addRemoteDestination( String name, Set<String> queuePointLocalizingSet, DestinationDefinition destinationDefinition) throws SIResourceException, SIIncorrectCallException { if (TraceComp...
python
def display(self, xaxis, alpha, new=True): """ E.display(xaxis, alpha = .8) :Arguments: xaxis, alpha Plots the CI region on the current figure, with respect to xaxis, at opacity alpha. :Note: The fill color of the envelope will be self.mass on the grayscale...
python
def _normalize_roots(file_roots): ''' Normalize file or pillar roots. ''' for saltenv, dirs in six.iteritems(file_roots): normalized_saltenv = six.text_type(saltenv) if normalized_saltenv != saltenv: file_roots[normalized_saltenv] = file_roots.pop(saltenv) if not isin...
java
public final void elementValueArrayInitializer() throws RecognitionException { int elementValueArrayInitializer_StartIndex = input.index(); try { if ( state.backtracking>0 && alreadyParsedRule(input, 70) ) { return; } // src/main/resources/org/drools/compiler/semantics/java/parser/Java.g:635:5: ( '{' ( elem...
java
public boolean updateImportTask(int importJobId, int importTaskId, AbstractRESTEntity updateTaskEntity) throws Exception { LOG.debug("Updating the import task " + importTaskId + " in job " + importJobId + " with " + updateTaskEntity); Response httpRespon...
python
def connect_get_namespaced_pod_portforward(self, name, namespace, **kwargs): # noqa: E501 """connect_get_namespaced_pod_portforward # noqa: E501 connect GET requests to portforward of Pod # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HT...
java
public static synchronized void register(final String serviceName, final Callable<Class< ? >> factory) { if ( serviceName == null ) { throw new IllegalArgumentException( "serviceName cannot be null" ); } if ( factory != null ) { ...
java
@SuppressWarnings("unchecked") public static <T> T unwrap(final T entity) { if (isProxy(entity)) { return (T) asProxy(entity).__unwrap(); } return entity; }
python
def filter_installed_packages(packages): """Return a list of packages that require installation.""" yb = yum.YumBase() package_list = yb.doPackageLists() temp_cache = {p.base_package_name: 1 for p in package_list['installed']} _pkgs = [p for p in packages if not temp_cache.get(p, False)] return...
java
public static CmsUgcSessionQueue createQueue(CmsUgcConfiguration config) { CmsUgcSessionQueue queue = new CmsUgcSessionQueue( config.needsQueue(), config.getQueueInterval().isPresent() ? config.getQueueInterval().get().longValue() : 0, config.getMaxQueueLength().isPresent() ...
java
@Nonnull public static String rescaleImageAndEncodeAsBase64(@Nonnull Image image, final int maxSize) throws IOException { final int width = image.getWidth(null); final int height = image.getHeight(null); final int maxImageSideSize = maxSize > 0 ? maxSize : Math.max(width, height); final float imageS...
java
public String getIndexTextForClassifications(String guid, List<AtlasClassification> classifications) throws AtlasBaseException { String ret = null; AtlasEntityWithExtInfo entityWithExtInfo = getAndCacheEntity(guid); if (entityWithExtInfo != null) { StringBuilder...
java
@Override protected void initGraphics() { super.initGraphics(); graphicListener = (o, ov, nv) -> { if (nv != null) { graphicContainer.getChildren().setAll(tile.getGraphic()); }}; titleText = new Text(); titleText.setFill(tile.getTitleColor()); Helper.enableNode(titleText, !tile...
java
public static String getShipType(BigInteger ts) { if (ts == null) return null; else return getShipType(ts.intValue()); }
python
def where(self, predicate): '''Filters elements according to whether they match a predicate. Note: This method uses deferred execution. Args: predicate: A unary function which is applied to each element in the source sequence. Source elements for which the predicate...
python
def get_highest_build_tool(sdk_version=None): """ Gets the highest build tool version based on major version sdk version. :param sdk_version(int) - sdk version to be used as the marjor build tool version context. Returns: A string containg the build tool version (default is 23.0.2 if none is found) """ ...
python
def on_add(self, item): """Convert to pseuso acces""" super(Tels, self).on_add(list_views.PseudoAccesCategorie(item))
java
@Override public CreateRegexPatternSetResult createRegexPatternSet(CreateRegexPatternSetRequest request) { request = beforeClientExecution(request); return executeCreateRegexPatternSet(request); }
java
public final String evaluateString( Message message ) throws JMSException { Object value = evaluate(message); if (value == null) return null; if (value instanceof String) return (String)value; throw new FFMQException("Expected a string but go...
java
private List<File> getUninstallDirs() { List<File> result = new ArrayList<File>(); File x = new File(name); if (!x.isDirectory()) x = x.getParentFile(); if (x.isDirectory()) result.add(x); result.add(eclipseIniPath.getParentFile()); return result; }
java
public java.util.List<String> getAlarmActions() { if (alarmActions == null) { alarmActions = new com.amazonaws.internal.SdkInternalList<String>(); } return alarmActions; }
python
def clip_extents(self): """Computes a bounding box in user coordinates covering the area inside the current clip. :return: A ``(x1, y1, x2, y2)`` tuple of floats: the left, top, right and bottom of the resulting extents, respectively. """ ext...
java
public static int lastIndexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return -1; } int sz = searchStrs.length; int ret = -1; int tmp = 0; for (int i = 0; i < sz; i++) { String search = searchStrs[i]; if (search ...
python
def url_params(request, except_params=None, as_is=False): """ create string with GET-params of request usage example: c['sort_url'] = url_params(request, except_params=('sort',)) ... <a href="{{ sort_url }}&sort=lab_number">Лабораторный номер</a> """ if not request.GET: ...
java
@Override public DescribeImportSnapshotTasksResult describeImportSnapshotTasks(DescribeImportSnapshotTasksRequest request) { request = beforeClientExecution(request); return executeDescribeImportSnapshotTasks(request); }
java
private int processIntDocument(int termIndex, int[] document, Matrix contextMatrix, int rowStart, BitSet featuresForTerm) { int contexts = 0; for (int i = 0; i < document.length; ++i) { ...
python
def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64): """Returns a key derived using the scrypt key-derivarion function N must be a power of two larger than 1 but no larger than 2 ** 63 (insane) r and p must be positive numbers such that r * p < 2 ** 30 The default values are: N...
java
public RemoteTask createRemoteTask(String strServer, String strRemoteApp, String strUserID, String strPassword) { RemoteTask remoteTask = super.createRemoteTask(strServer, strRemoteApp, strUserID, strPassword); return remoteTask; }
java
public void setYoaBase(Integer newYoaBase) { Integer oldYoaBase = yoaBase; yoaBase = newYoaBase; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.MEASUREMENT_UNITS__YOA_BASE, oldYoaBase, yoaBase)); }
java
public static dnskey[] get(nitro_service service, String keyname[]) throws Exception{ if (keyname !=null && keyname.length>0) { dnskey response[] = new dnskey[keyname.length]; dnskey obj[] = new dnskey[keyname.length]; for (int i=0;i<keyname.length;i++) { obj[i] = new dnskey(); obj[i].set_keyname(key...
java
private static String containsDuplicates(List<BindingTuple> tuples) { Set<String> sigs = new HashSet<String>(); for (BindingTuple tuple : tuples) { if (!sigs.add(printSig(tuple.parameterized))) return printSig(tuple.parameterized); } return null; }
java
@Override public List<CommerceAddressRestriction> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
public static void add(Element parent, NodeList list) { int size; int i; size = list.getLength(); for (i = 0; i < size; i++) { addNode(parent, list.item(i)); } }
java
static Iterator<MutableLongTuple> wrappingIterator( LongTuple bounds, Iterator<? extends MutableLongTuple> delegate) { return wrappingIteratorInternal(LongTuples.copy(bounds), delegate); }
python
def is_imagej(self): """Return ImageJ description if exists, else None.""" for description in (self.description, self.description1): if not description: return None if description[:7] == 'ImageJ=': return description return None
java
@Override public final void backupDatabase(final String pDbName) throws Exception { String dbPath = this.databaseDir + File.separator + pDbName + ".sqlite"; File dbFile = new File(dbPath); if (dbFile.exists()) { String encPath = this.backupDir + File.separator + pDbName + ".sqlten"; File dbBkF...
java
private String getSelectPkSql(String[] where) { StringBuilder sql = new StringBuilder("select ") .append(_entityInfo.id().columnName()) .append(" FROM ").append(_entityInfo.tableName()) .append(" where "); for (int i = 0; i < where.length; i++) { sql.append(where[i]).append('=').appen...
python
def get_default_config(self): """ Returns the xfs collector settings """ config = super(XFSCollector, self).get_default_config() config.update({ 'path': 'xfs' }) return config
python
def _check_data_flow_id(self, data_flow): """Checks the validity of a data flow id Checks whether the id of the given data flow is already by anther data flow used within the state. :param rafcon.core.data_flow.DataFlow data_flow: The data flow to be checked :return bool validity, str ...
python
def AddOption(self, descriptor, constant=False): """Registers an option with the configuration system. Args: descriptor: A TypeInfoObject instance describing the option. constant: If this is set, the option is treated as a constant - it can be read at any time (before parsing the configurat...
python
def AddProcessingOptions(self, argument_group): """Adds the processing options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group. """ argument_group.add_argument( '--single_process', '--single-process', dest='single_process', action='st...
java
public void cancel(final int id) { final BaseNotificationItem notification = remove(id); if (notification == null) { return; } notification.cancel(); }
python
def _find_dependant_trees(self, tree_obj): """ returns list of trees that are dependent_on given tree_obj """ dependant_trees = [] for tree_name, tree in self.trees.items(): if tree_obj in tree.dependent_on: dependant_trees.append(tree) return dependant_trees
python
def taskfile_updated_data(file_, role): """Return the data for updated date :param file_: the file that holds the data :type file_: :class:`jukeboxcore.djadapter.models.File` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the updated date :rtype: depending...
java
public java.util.List<MinimumEngineVersionPerAllowedValue> getMinimumEngineVersionPerAllowedValue() { if (minimumEngineVersionPerAllowedValue == null) { minimumEngineVersionPerAllowedValue = new com.amazonaws.internal.SdkInternalList<MinimumEngineVersionPerAllowedValue>(); } return m...
python
def selectedParameterTypes(self, row): """Gets a list of the intersection of the editable properties in the parameteter *param*'s component selection. E.g. ['frequency', 'intensity'] :param row: the ith parameter number :type row: int :returns: list<str> -- a list of AbstractSti...
python
def subset(self, fromdate, todate): ''' Return a list of dates from the list between <fromdate> and <todate> (inclusive) ''' #CONSIDER: raise an exception if a date is not in self i_from = self.index(fromdate) if fromdate != self[i_from]: # don't go back befor...
java
public boolean dispatchKeyEvent (KeyEvent e) { // bail if we're not enabled, we haven't the focus, or we're not // showing on-screen if (!_enabled || !_focus || !_target.isShowing()) { // log.info("dispatchKeyEvent [enabled=" + _enabled + // ", focus=" + _foc...
python
def symmetricsys(dep_tr=None, indep_tr=None, SuperClass=TransformedSys, **kwargs): """ A factory function for creating symmetrically transformed systems. Creates a new subclass which applies the same transformation for each dependent variable. Parameters ---------- dep_tr : pair of callables (defa...
python
def density_2d(self, r, kwargs_profile): """ computes the projected density along the line-of-sight :param r: radius (arcsec) :param kwargs_profile: keyword argument list with lens model parameters :return: 2d projected density at projected radius r """ kwargs = c...
java
public synchronized Registry getRegistry() throws RemoteException { if (registry == null) { registry = LocateRegistry.createRegistry(JdcpUtil.DEFAULT_PORT); } return registry; }
java
public void eventReceived (DEvent event) { if (event instanceof InvocationResponseEvent) { InvocationResponseEvent ire = (InvocationResponseEvent)event; handleInvocationResponse(ire.getRequestId(), ire.getMethodId(), ire.getArgs()); } else if (event instanceof InvocationNoti...
python
def import_class(import_str): """Returns a class from a string including module and class.""" mod_str, _sep, class_str = import_str.rpartition('.') try: __import__(mod_str) return getattr(sys.modules[mod_str], class_str) except (ValueError, AttributeError): raise ImportError('Cla...
python
def _find_conflict( context, # type: ValidationContext cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]] compared_fragments, # type: PairSet parent_fields_are_mutually_exclu...
java
public String [] getNames() { String [] result = new String[headers.size()]; headers.keySet().toArray(result); return result; }
java
public void removeResourceFromUsersPubList(CmsObject cms, Collection<CmsUUID> structureIds) throws CmsException { m_securityManager.removeResourceFromUsersPubList(cms.getRequestContext(), structureIds); }