language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static final void parseExtendedAttribute(ProjectFile file, FieldContainer mpx, String value, FieldType mpxFieldID, TimeUnit durationFormat) { if (mpxFieldID != null) { switch (mpxFieldID.getDataType()) { case STRING: { mpx.set(mpxFieldID, va...
python
def get_queryset(self): """ Return the first preferences object for the current site. If preferences do not exist create it. """ queryset = super(SingletonManager, self).get_queryset() # Get current site current_site = None if getattr(settings, 'SITE_ID'...
python
def read_credentials(fname): """ read a simple text file from a private location to get username and password """ with open(fname, 'r') as f: username = f.readline().strip('\n') password = f.readline().strip('\n') return username, password
python
def _get_service_names(self): """ Get a list of service names from Sentinel. Tries Sentinel hosts until one succeeds; if none succeed, raises a ConnectionError. :return: the list of service names from Sentinel. """ master_info = None connection_errors = [] ...
python
def set_result_type(self, result_type): """ Sets 'result_type' parameter to specify what type of search \ results you would prefer to receive. The current default is “mixed.” \ Valid values include: \ - mixed: Include both popular and real time results \ - recent: return ...
java
public void setMaxParallelism(int maxParallelism) { Preconditions.checkArgument(maxParallelism > 0 && maxParallelism <= StreamGraphGenerator.UPPER_BOUND_MAX_PARALLELISM, "Maximum parallelism must be between 1 and " + StreamGraphGenerator.UPPER_BOUND_MAX_PARALLELISM + ". Found: " + maxParallelism); t...
java
public static synchronized void removeTruncationRecord(UUID cfId) { String req = "DELETE truncated_at[?] from system.%s WHERE key = '%s'"; executeInternal(String.format(req, LOCAL_CF, LOCAL_KEY), cfId); truncationRecords = null; forceBlockingFlush(LOCAL_CF); }
java
public void setOptions(Set<Option> options) { this.options = (options == null) ? Collections.<Option>emptySet() : new HashSet<Option>(options); }
java
public static List<String> removeNotes(Collection<String> logLines) { List<String> r = new ArrayList<>(logLines.size()); for (String l : logLines) r.add(removeNotes(l)); return r; }
java
public List<Class<?>> resolveFieldGenerics(final Field field) { return switchContext4field(field).resolveGenericsOf(field.getGenericType()); }
python
def remove(self, *labelvalues): if not self._labelnames: raise ValueError('No label names were set when constructing %s' % self) """Remove the given labelset from the metric.""" if len(labelvalues) != len(self._labelnames): raise ValueError('Incorrect label count (expect...
python
def get_proof(self): """ Get a proof produced when deciding the formula. """ if self.lingeling and self.prfile: self.prfile.seek(0) return [line.rstrip() for line in self.prfile.readlines()]
python
def _vksdesc(d): ''' d = {'a':1,'b':2,'c':2,'d':4} desc = _vksdesc(d) pobj(desc) ''' pt = copy.deepcopy(d) seqs_for_del =[] vset = set({}) for k in pt: vset.add(pt[k]) desc = {} for v in vset: desc[v] = [] for k in pt: desc[pt[k]].appen...
java
private @Nonnull Collection<FirewallRule> toFirewallRules(@Nonnull List<com.google.api.services.compute.model.Firewall> rules){ ArrayList<FirewallRule> firewallRules = new ArrayList<FirewallRule>(); for(com.google.api.services.compute.model.Firewall googleRule : rules) { List<RuleTarget> sou...
python
def asum(data, axis=None, mapper=None, blen=None, storage=None, create='array', **kwargs): """Compute the sum.""" return reduce_axis(data, axis=axis, reducer=np.sum, block_reducer=np.add, mapper=mapper, blen=blen, storage=storage, create=create, **kwargs)
java
public static <X, Y> Y getValue(X target, String propertyPath) { return getValue(target, propertyPath, null); }
python
def setSpecialPrice(self, product, special_price=None, from_date=None, to_date=None, store_view=None, identifierType=None): """ Update product's special price :param product: ID or SKU of product :param special_price: Special Price ...
java
public String extractToString(final String separator, final String endSeparator) throws DevFailed { logger.debug(LOG_EXTRACTING, this); return attributeImpl.extractToString(separator, endSeparator); }
java
public String print(String fqn) { Node n=findNode(fqn); if(n == null) return null; return n.toString(); }
python
def require_session(handler): """ Decorator to ensure a session is properly in the request """ @functools.wraps(handler) async def decorated(request: web.Request) -> web.Response: request_session_token = request.match_info['session'] session = session_from_request(request) if not ses...
java
@Deprecated public static void setLogger(@Nullable final Logger logger) { LogOptions.Logger loggerToSet = logger == null ? logcatLogger : new LogOptions.Logger() { @Override public void log(int level, String tag, String msg) { logger.lo...
python
def kernel_version(self): """ Returns the kernel kernel version of the remote host """ result = self.shell.execute(self.commands.kernel_version.value) stdout = self.shell.decode(result['stdout']) stderr = self.shell.decode(result['stderr']) return stdout
python
def get_xsession(self, item): """ Returns the XNAT session and cache dir corresponding to the item. """ subj_label, sess_label = self._get_item_labels(item) with self: xproject = self._login.projects[self.project_id] try: xsubject =...
python
def generate_blastdb_commands(filenames, outdir, blastdb_exe=None, mode="ANIb"): """Return a list of makeblastdb command-lines for ANIb/ANIblastall - filenames - a list of paths to input FASTA files - outdir - path to output directory - blastdb_exe - path to the makeblastdb executable """ if mo...
python
def file(ui, repo, clname, pat, *pats, **opts): """assign files to or remove files from a change list Assign files to or (with -d) remove files from a change list. The -d option only removes files from the change list. It does not edit them or remove them from the repository. """ if codereview_disabled: raise...
java
private String getAlgName(int ch, int choice) { /* Only the normative character name can be algorithmic. */ if (choice == UCharacterNameChoice.UNICODE_CHAR_NAME || choice == UCharacterNameChoice.EXTENDED_CHAR_NAME ) { // index in terms integer index synchr...
java
private void unpackFile(File file) throws MojoExecutionException { // initialize unpacker to validate patterns ContentUnpackerProperties props = new ContentUnpackerProperties(); props.setExcludeFiles(this.excludeFiles); props.setExcludeNodes(this.excludeNodes); props.setExcludeProperties(this.exclu...
python
def __write_docstring_return_type(self): """ Writes the return type part of the docstring for the wrapper method of a stored routine. """ rtype = self._get_docstring_return_type() if rtype: self._write_line('') self._write_line(':rtype: {0}'.format(rtype))
java
public void updateToAccepted(long tick, AIProtocolItem acceptedItem) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry( tc, "updateToAccepted", new Object[] { Long.valueOf(tick), acceptedItem }); _targetStream.setCursor(tick); TickRange tr = _tar...
java
public Integer getTextureMagFilter(AiTextureType type, int index) { checkTexRange(type, index); Property p = getProperty(PropertyKey.TEX_MAG_FILTER.m_key); if (null == p || null == p.getData()) { return (Integer) m_defaults.get(PropertyKey.TEX_MAG_FILTER); } Object ...
java
public Config setDurableExecutorConfigs(Map<String, DurableExecutorConfig> durableExecutorConfigs) { this.durableExecutorConfigs.clear(); this.durableExecutorConfigs.putAll(durableExecutorConfigs); for (Entry<String, DurableExecutorConfig> entry : durableExecutorConfigs.entrySet()) { ...
java
public final int indexOf(Object elem, int index) { for (int i = index; i < m_firstFree; i++) { if (m_map[i] == elem) return i; } return java.lang.Integer.MIN_VALUE; }
python
def get_user(self, username): """ Given the verified username, look up and return the corresponding user account if it exists, or raising ``ActivationError`` if it doesn't. """ User = get_user_model() try: user = User.objects.get(**{ U...
java
@Override public int getInt( final String key, final int defaultValue ) { return formatInt( key, getFormattedPropValue( key ), defaultValue ); }
python
def ret_glob_minions(self): ''' Return minions that match via glob ''' fnfilter = functools.partial(fnmatch.filter, pat=self.tgt) return self._ret_minions(fnfilter)
python
def _hook_variable_gradient_stats(self, var, name, log_track): """Logs a Variable's gradient's distribution statistics next time backward() is called on it. """ if not isinstance(var, torch.autograd.Variable): cls = type(var) raise TypeError('Expected torch.Variab...
java
public Matrix4d setLookAlong(double dirX, double dirY, double dirZ, double upX, double upY, double upZ) { // Normalize direction double invDirLength = 1.0 / Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ); dirX *= -invDirLength; dirY *= -invDirLength; ...
java
private void ensureConversion(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException { if (CHECKLEVEL_NONE.equals(checkLevel)) { return; } // we issue a warning if we encounter a field with a java.util.Date java type without a conversion ...
python
def _check_index_within_index_pairs(index, index_ranges): """ Check that the index 'index' lies within the set of indexes. :param index: Index to determine whether it falls within the range or index pairs. :param index_ranges: A list of index pairs, monotonically increasing pairs. :return: True if t...
java
@Override public void cacheResult( List<CommercePaymentMethodGroupRel> commercePaymentMethodGroupRels) { for (CommercePaymentMethodGroupRel commercePaymentMethodGroupRel : commercePaymentMethodGroupRels) { if (entityCache.getResult( CommercePaymentMethodGroupRelModelImpl.ENTITY_CACHE_ENABLED, Commer...
java
public static Validator<CharSequence> maxLength(@NonNull final CharSequence errorMessage, final int maxLength) { return new MaxLengthValidator(errorMessage, maxLength); }
python
def _print_foreign_playlist_message(self): """ reset previous message """ self.operation_mode = self.window_mode = NORMAL_MODE self.refreshBody() """ display new message """ txt='''A playlist by this name: __"|{0}|" already exists in the config directory. ...
java
public final File scanForFile(final ProviderIdent ident) throws PluginScannerException { if (!extdir.exists() || !extdir.isDirectory()) { return null; } return scanFor(ident, extdir.listFiles(getFileFilter())); }
java
@Override public ClosableDataBuilder<MB> getDataBuilder(final Object consumer, final boolean notifyChange) { return new ClosableDataBuilder<>(getBuilderSetup(), consumer, notifyChange); }
python
def GetDate(text=None, selected=None, **kwargs): """Prompt the user for a date. This will raise a Zenity Calendar Dialog for the user to pick a date. It will return a datetime.date object with the date or None if the user hit cancel. text - Text to be displayed in the calendar dialog. ...
java
private void setBar(final double VALUE) { double factor = VALUE / gauge.getRange(); Color barColor = gauge.getBarColor(); if (gauge.isGradientBarEnabled() && !gauge.getGradientBarStops().isEmpty()) { barColor = gauge.getGradientLookup().getColorAt(factor); } else if (gauge.ge...
python
def to_tuple(self): '''Convert the source sequence to a tuple. Note: This method uses immediate execution. ''' if self.closed(): raise ValueError("Attempt to call to_tuple() on a closed Queryable.") if isinstance(self._iterable, tuple): return self._iter...
java
public static boolean isUpperCase(final String value) { validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER); for (int i = 0; i < value.length(); i++) { if (Character.isLowerCase(value.charAt(i))) { return false; } } return true; }
java
public ThymeleafEngineConfigBuilder<P> setTemplateResolver(final ITemplateResolver templateResolver) { templateResolvers().clear(); templateResolvers().add(templateResolver); return this; }
python
def filter_keys(cls, data): """Filter GELF record keys using exclude_patterns :param dict data: Log record has dict :return: the filtered log record :rtype: dict """ keys = list(data.keys()) for pattern in cls.EXCLUDE_PATTERNS: for key in keys: ...
python
def run_script_api(module_name): '''API handler. Take script input (from script_input above), run the run() function, and return the results''' filename = '' file_stream = '' #form = {k : try_json(v) for k,v in request.values.items()} form = request.values.to_dict(flat=False) if request.json...
java
public static void setSyncCache(String name, Cache cache) { if (null == name || "".equals(name.trim()) || null == cache) { return; } GlobalSyncRedis.caches.put(name, cache); }
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.IMAGE_SIZE__UNITBASE: setUNITBASE(UNITBASE_EDEFAULT); return; case AfplibPackage.IMAGE_SIZE__HRESOL: setHRESOL(HRESOL_EDEFAULT); return; case AfplibPackage.IMAGE_SIZE__VRESOL: setVRESOL(VRESOL_EDEFAULT)...
python
def get_node_msindex(msinds, node_seed): """ Convert seeds-like selection of voxel to multiscale index. :param msinds: ndarray with indexes :param node_seed: ndarray with 1 where selected pixel is, or list of indexes in this array :return: multiscale index of first found seed """ if type(nod...
python
def retrieve_tx(self, txid): """Returns rawtx for <txid>.""" txid = deserialize.txid(txid) tx = self.service.get_tx(txid) return serialize.tx(tx)
java
public static String getFqdnHost(InetSocketAddress addr) { Preconditions.checkNotNull(addr.getAddress(), "the address of " + addr + " is invalid."); return addr.getAddress().getCanonicalHostName(); }
java
public static boolean canPresentOpenGraphActionDialog(Context context, OpenGraphActionDialogFeature... features) { return handleCanPresent(context, EnumSet.of(OpenGraphActionDialogFeature.OG_ACTION_DIALOG, features)); }
python
def fix_jp2_image(image, bit_depth): """Because Pillow library incorrectly reads JPEG 2000 images with 15-bit encoding this function corrects the values in image. :param image: image read by opencv library :type image: numpy array :param bit_depth: bit depth of jp2 image encoding :type bit_dept...
java
@Override public SortedSet<Cell<V>> cells() { return new ForwardingSortedSet<Cell<V>>() { @Override protected SortedSet<Cell<V>> delegate() { return cells; } @Override public boolean add(Cell<V> element) { return sup...
python
def ttl(self): """Get actual ttl in seconds. :return: actual ttl. :rtype: float """ # result is self ts result = getattr(self, Annotation.__TS, None) # if result is not None if result is not None: # result is now - result now = ti...
java
public Whitelist removeAttributes(String tag, String... attributes) { Validate.notEmpty(tag); Validate.notNull(attributes); Validate.isTrue(attributes.length > 0, "No attribute names supplied."); TagName tagName = TagName.valueOf(tag); Set<AttributeKey> attributeSet = new HashSe...
python
def alignment(layer, decay_ratio=2): """Encourage neighboring images to be similar. When visualizing the interpolation between two objectives, it's often desireable to encourage analagous boejcts to be drawn in the same position, to make them more comparable. This term penalizes L2 distance between neighbor...
java
public List<Long> searchPartially(File f, byte[] searchBytes, long startPosition, long maxSizeToRead) { if (USE_NIO) { return searchPartiallyUsingNIO(f, searchBytes, startPosition, maxSizeToRead, null); } else { return searchPartiallyUsingLegacy(f, searchBytes, startPosition, maxSizeToRead, null); } }
python
def _enumerate_directions(x): """ For an n-dimensional tensor, returns tensors to enumerate each axis. >>> x = np.zeros([2, 3, 4]) # or any other tensor >>> i, j, k = _enumerate_directions(x) >>> result = i + 2 * j + 3 * k result[i, j, k] = i + 2 * j + 3 * k, and also has the same shape as resu...
python
def missingkeys_nonstandard(block, commdct, dtls, objectlist, afield='afiled %s'): """This is an object list where thre is no first field name to give a hint of what the first field name should be""" afield = 'afield %s' for key_txt in objectlist: key_i = dtls.index(key_txt.upper()) comm...
python
def main(): """ Commandline interface to average parameters. """ setup_main_logger(console=True, file_logging=False) params = argparse.ArgumentParser(description="Averages parameters from multiple models.") arguments.add_average_args(params) args = params.parse_args() average_parameters(...
python
def read(self, x): """Read from the memory. An external component can use the results via a simple MLP, e.g., fn(x W_x + retrieved_mem W_m). Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: access_logits: the logits for accessing the memory in shape of ...
python
def bind(self, func: Callable[[Any], IO]) -> 'Put': """IO a -> (a -> IO b) -> IO b""" text, a = self._value return Put(text, a.bind(func))
java
public void marshall(ESInstanceDetails eSInstanceDetails, ProtocolMarshaller protocolMarshaller) { if (eSInstanceDetails == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(eSInstanceDetails.getInstanc...
java
public SearchResponse searchAll(String index, String type) { return searchAll(JMArrays.buildArray(index), type); }
java
public synchronized Boolean isChecked(V object) { if(object == null) return null; if(indexOf(object) == -1) return null; return checkedIndex == indexOf(object); }
java
public static byte[] decryptBase64_3DES(byte[] data, byte[] key) { try { return decrypt3DES(Base64.getDecoder().decode(data), key); } catch (Exception e) { return null; } }
python
def relabel_atoms(self, start=1): """Relabels all Atoms in numerical order, offset by the start parameter. Parameters ---------- start : int, optional Defines an offset for the labelling. """ counter = start for atom in self.get_atoms(ligands=True): ...
java
private Node tryFoldParseNumber( Node n, String functionName, Node firstArg) { checkArgument(n.isCall()); boolean isParseInt = functionName.equals("parseInt"); Node secondArg = firstArg.getNext(); // Second argument is only used as the radix for parseInt int radix = 0; if (secondArg != n...
java
public boolean deletePermissionForUser(String user, List<String> permission) { return deletePermissionForUser(user, permission.toArray(new String[0])); }
java
public Observable<ServiceEndpointPolicyInner> beginCreateOrUpdateAsync(String resourceGroupName, String serviceEndpointPolicyName, ServiceEndpointPolicyInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serviceEndpointPolicyName, parameters).map(new Func1<ServiceResponse<S...
java
@Nullable Socket releaseConnectionNoEvents() { assert (Thread.holdsLock(connectionPool)); int index = -1; for (int i = 0, size = this.connection.transmitters.size(); i < size; i++) { Reference<Transmitter> reference = this.connection.transmitters.get(i); if (reference.get() == this) { i...
java
void postFailure(final DownloadRequest request, final int statusCode, final String errMsg) { downloadPoster.execute(new Runnable() { @Override public void run() { request.downloadCallback().onFailure(request.downloadId(), statusCode, errMsg); } }); }
java
static String decodeString(ByteBuf in) throws UnsupportedEncodingException { if (in.readableBytes() < 2) { return null; } //int strLen = Utils.readWord(in); int strLen = in.readUnsignedShort(); if (in.readableBytes() < strLen) { return null; } ...
python
def get_protection(self): """ :calls: `GET /repos/:owner/:repo/branches/:branch/protection <https://developer.github.com/v3/repos/branches>`_ """ headers, data = self._requester.requestJsonAndCheck( "GET", self.protection_url, headers={'Accept': Consts...
java
@SuppressWarnings("WeakerAccess") public ApiFuture<Void> deleteTableAsync(String tableId) { DeleteTableRequest request = DeleteTableRequest.newBuilder().setName(getTableName(tableId)).build(); return transformToVoid(this.stub.deleteTableCallable().futureCall(request)); }
java
public static <T extends Enum<T>> T random(Class<T> enumClass) { EnumSet<T> enums = EnumSet.allOf(enumClass); return IterableUtils.randomFrom(enums); }
python
def get_sections_file_parser(file): """ Returns a sections file parser. :param file: File. :type file: unicode :return: Parser. :rtype: SectionsFileParser """ if not foundations.common.path_exists(file): raise foundations.exceptions.FileExistsError( "{0} | '{1}' sec...
java
public NotificationChain basicSetImplicitFirstArgument(XExpression newImplicitFirstArgument, NotificationChain msgs) { XExpression oldImplicitFirstArgument = implicitFirstArgument; implicitFirstArgument = newImplicitFirstArgument; if (eNotificationRequired()) { ENotificationImpl notification = new ENotifica...
java
@Override public List<JobDef> getJobDefinitions() { try { return target.path("jd").request().get(new GenericType<List<JobDef>>() { }); } catch (Exception e) { throw new JqmClientException(e); } }
java
public void addContentHandler(Class<? extends Content> clazz, JavaMailContentHandler handler) { map.put(clazz, handler); }
java
public boolean registerCollection(CollectionSchema.MessageFactory factory) { return null == collectionMapping.putIfAbsent(factory.typeClass() .getName(), factory); }
python
def packages( state, host, packages=None, present=True, latest=False, update=False, cache_time=None, upgrade=False, force=False, no_recommends=False, allow_downgrades=False, ): ''' Install/remove/update packages & update apt. + packages: list of packages to ensure + present: whether...
python
def orientnii(imfile): '''Get the orientation from NIfTI sform. Not fully functional yet.''' strorient = ['L-R', 'S-I', 'A-P'] niiorient = [] niixyz = np.zeros(3,dtype=np.int8) if os.path.isfile(imfile): nim = nib.load(imfile) pct = nim.get_data() A = nim.get_sform() ...
python
def _augment_url_with_version(auth_url): """Optionally augment auth_url path with version suffix. Check if path component already contains version suffix and if it does not, append version suffix to the end of path, not erasing the previous path contents, since keystone web endpoint (like /identity) co...
java
public GetEnvironmentResponseInner getEnvironment(String userName, String environmentId) { return getEnvironmentWithServiceResponseAsync(userName, environmentId).toBlocking().single().body(); }
java
private Constant readConstant() throws InvalidClassFileFormatException, IOException { int tag = in.readUnsignedByte(); if (tag < 0 || tag >= CONSTANT_FORMAT_MAP.length) { throw new InvalidClassFileFormatException(expectedClassDescriptor, codeBaseEntry); } String format = CONS...
python
def _install_yarnpkg(self): """Install the Yarnpkg distribution from pants support binaries. :returns: The Yarnpkg distribution bin path. :rtype: string """ yarnpkg_package_path = YarnpkgDistribution.scoped_instance(self).select() yarnpkg_bin_path = os.path.join(yarnpkg_package_path, 'dist', 'b...
java
@Override public void serialize(final DataOutput pOutput) throws TTIOException { try { pOutput.writeInt(IConstants.NAMESPACE); mDel.serialize(pOutput); mNameDel.serialize(pOutput); } catch (final IOException exc) { throw new TTIOException(exc); ...
python
def stop_Note(self, note): """Add a note_off event for note to event_track.""" velocity = 64 channel = 1 if hasattr(note, 'dynamics'): if 'velocity' in note.dynamics: velocity = note.dynamics['velocity'] if 'channel' in note.dynamics: ...
java
public synchronized void initialize(CmsObject cms, CmsConfigurationManager configurationManager) throws CmsRoleViolationException { if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_1_CORE_OBJECT) { // certain test cases won't have an OpenCms context OpenCms.getRoleManager().checkRole(cm...
java
public void appendDirtyObject (SceneObject scobj) { DirtyItem item = getDirtyItem(); item.init(scobj, scobj.info.x, scobj.info.y); _items.add(item); }
java
@Override public AnalysisJob read(final InputStream inputStream) throws NoSuchDatastoreException, NoSuchColumnException, NoSuchComponentException, ComponentConfigurationException, IllegalStateException { try (AnalysisJobBuilder ajb = create(inputStream)) { return ajb.toAn...
java
public void marshall(DeleteGroupRequest deleteGroupRequest, ProtocolMarshaller protocolMarshaller) { if (deleteGroupRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteGroupRequest.getGro...
python
def _create_diff(diff, fun, key, prev, curr): ''' Builds the diff dictionary. ''' if not fun(prev): _create_diff_action(diff, 'added', key, curr) elif fun(prev) and not fun(curr): _create_diff_action(diff, 'removed', key, prev) elif not fun(curr): _create_diff_action(di...