language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _resetWidgets(self): """Resets all widgets of this dialog to its inital state. """ self._filenameLineEdit.setText('') self._encodingComboBox.setCurrentIndex(self._idx) self._delimiterBox.reset() self._headerCheckBox.setChecked(False) self._statusBar.showMessa...
java
public Boolean getPropertyAsBoolean(final String bundleName, final String key) { LOG.info("Getting value for key: " + key + " from bundle name: " + bundleName); ResourceBundle bundle = bundles.get(bundleName); Boolean result = Boolean.FALSE; try { result = Boolean.valueOf(bundle.getString(key)); } c...
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.CTC__CON_DATA: setConData((byte[])newValue); return; } super.eSet(featureID, newValue); }
python
def ellipticities(I_xy, x, y): """ compute ellipticities of a light distribution :param I_xy: :param x: :param y: :return: """ Q_xx, Q_xy, Q_yy, bkg = moments(I_xy, x, y) norm = Q_xx + Q_yy + 2 * np.sqrt(Q_xx*Q_yy - Q_xy**2) e1 = (Q_xx - Q_yy) / norm e2 = 2 * Q_xy / norm ...
java
@Override public byte[] getBytes(K key) { if(key == null) { return null; } return _store.get(_keySerializer.serialize(key)); }
java
@Override public final void persist(Object e) { checkClosed(); checkTransactionNeeded(); try { getPersistenceDelegator().persist(e); } catch (Exception ex) { // onRollBack. doRollback(); throw ne...
java
public void register() { logger.debug("[register] uri = {}", getManagementUri()); JsonNode jsonNode; ObjectMapper objectMapper = jsonObjectMapper.getObjectMapperBinary(); ObjectNode objectNode = objectMapper.createObjectNode(); objectNode.put(CommandParameters.METHOD, "register"...
python
def child_get_property(self, child, property_name, value=None): """child_get_property(child, property_name, value=None) :param child: a widget which is a child of `self` :type child: :obj:`Gtk.Widget` :param property_name: the name of the property to get ...
python
def post_presign_signature(date, region, secret_key, policy_str): """ Calculates signature version '4' for POST policy string. :param date: datetime formatted date. :param region: region of the bucket for the policy. :param secret_key: Amazon S3 secret access key. :param policy_str: policy stri...
python
def _find_bounding_points(self, x, y): """ Find the indices of the grid points that bound the input ``(x, y)`` position. Parameters ---------- x, y : float The ``(x, y)`` position where the PSF is to be evaluated. Returns ------- indi...
python
def OnExpandAll(self): """ expand all nodes """ root = self.tree.GetRootItem() fn = self.tree.Expand self.traverse(root, fn) self.tree.Expand(root)
python
def read(author, kind): """ Attempts to read the cache to fetch missing arguments. This method will attempt to find a '.license' file in the 'CACHE_DIRECTORY', to read any arguments that were not passed to the license utility. Arguments: author (str): The author passed, if any. k...
python
def ftp_proxy(self, value): """ Sets ftp proxy setting. :Args: - value: The ftp proxy value. """ self._verify_proxy_type_compatibility(ProxyType.MANUAL) self.proxyType = ProxyType.MANUAL self.ftpProxy = value
java
protected void createConnection(ConnectionContext context) throws JMSException { if (context == null) { throw new IllegalStateException("The context is null"); } ConnectionFactory factory = getConnectionFactory(); Connection conn = factory.createConnection(); context....
java
protected void addActionKeyBinding(KeyStroke key, String actionKey, Action action) { getInputMap().put(key, actionKey); getActionMap().put(actionKey, action); }
java
public long getAvailableBytes(BlockStoreLocation location) { long spaceAvailable = 0; if (location.equals(BlockStoreLocation.anyTier())) { for (StorageTier tier : mTiers) { spaceAvailable += tier.getAvailableBytes(); } return spaceAvailable; } String tierAlias = location.tier...
python
def get_entity(self): """ Returns the entity converted from the proxied data. """ if self._accessor is None: if self.__converted_entity is None: self.__converted_entity = self._convert_to_entity() else: # If we have an accessor, we can get ...
python
def get_tunnel_statistics_output_tunnel_stat_tx_frames(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_tunnel_statistics = ET.Element("get_tunnel_statistics") config = get_tunnel_statistics output = ET.SubElement(get_tunnel_statistics, "outpu...
python
def get_changes(self, serialized=False, keep=False): """ Get a journal of changes that have occurred :param `serialized`: Return changes in the serialized format used by TaskWarrior. :param `keep_changes`: By default, the list of changes is reset after running ...
java
public int getEnergies(IAtom sourceAtom, IAtom targetAtom, Order bondOrder) { int dKJPerMol = -1; for (Map.Entry<Integer, BondEnergy> entry : bondEngergies.entrySet()) { BondEnergy bondEnergy = entry.getValue(); String atom1 = bondEnergy.getSymbolFirstAtom(); String ...
java
public String compile(String resourcePath, String coffeeScriptSource) { String result = null; try { result = (String) jsEngine.invokeMethod(coffeeScript, "compile", coffeeScriptSource, options); } catch (NoSuchMethodException | ScriptException e) { throw new BundlingProcessException(e); } return resul...
java
public void addAndSaveUserPermissions(E entity, User user, Permission... permissions) { if (entity == null) { LOG.error("Could not add permissions: The passed entity is NULL."); return; } // create a set from the passed array final HashSet<Permission> permissions...
java
public void callAppenders(LoggingEvent event) { int writes = 0; for (Category c = this; c != null; c = c.parent) { writes += c.aai.appendLoopOnAppenders(event); if (!c.additive) { break; } } if (writes == 0) { repository.e...
python
def set_agent(self, short_name, client_id): """Register a client id that handlers commands for a service. Args: short_name (str): The name of the service to set an agent for. client_id (str): A globally unique id for the client that should receive...
python
def import_product_sets( self, parent, input_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Asynchronous API that imports a list of reference images to specified pro...
java
public static AssetUpdater updater(final String pathServiceSid, final String pathSid, final String friendlyName) { return new AssetUpdater(pathServiceSid, pathSid, friendlyName); }
java
protected static final List<Entry> copy (final List<Entry> entries) { if (entries == null) return null; final ArrayList<Entry> copy = new ArrayList<>(); for (Entry e : entries) copy.add(e.copy()); return copy; } /** * The abstract constructor. * <...
python
def createCorrFile(outfile, arrlist, template): """ Create a _cor file with the same format as the original input image. The DQ array will be replaced with the mask array used to create the _cor file. """ # Remove the existing cor file if it exists if os.path.isfile(outfile): os.rem...
python
def main(): """ NAME nrm_specimens_magic.py Note: this program has been deprecated and is not maintained DESCRIPTION converts NRM data in a measurements type file to geographic and tilt corrected data in a specimens type file SYNTAX ...
java
String subCommand(String cmd, ArgTokenizer at, String[] subs) { at.allowedOptions("-retain"); String sub = at.next(); if (sub == null) { // No sub-command was given return at.hasOption("-retain") ? "_retain" : "_blank"; } ...
python
def get_fork_sync_request(self, repository_name_or_id, fork_sync_operation_id, project=None, include_links=None): """GetForkSyncRequest. [Preview API] Get a specific fork sync operation's details. :param str repository_name_or_id: The name or ID of the repository. :param int fork_sync_op...
java
public Object invoke (Object proxy, Method method, Object[] args) throws Throwable { if (isCorrectMethod(method, args)) { boolean handled = callTarget(args[0]); setApplicationEventHandled(args[0], handled); } // All of the ApplicationListener methods are void; return null...
python
def authentication_required(req, resp, resource, uri_kwargs): """Ensure that user is authenticated otherwise return ``401 Unauthorized``. If request fails to authenticate this authorization hook will also include list of ``WWW-Athenticate`` challenges. Args: req (falcon.Request): the request o...
java
private static String manifestAsString(Manifest manifest) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { manifest.write(baos); return baos.toString("UTF-8"); } catch (IOException e) { throw new IllegalStateException("Unable to write MANIFES...
python
def use_gl(target='gl2'): """ Let Vispy use the target OpenGL ES 2.0 implementation Also see ``vispy.use()``. Parameters ---------- target : str The target GL backend to use. Available backends: * gl2 - Use ES 2.0 subset of desktop (i.e. normal) OpenGL * gl+ - Use the ...
java
public static IndexOutOfBoundsException newIndexOutOfBoundsException(String message, Object... args) { return newIndexOutOfBoundsException(null, message, args); }
python
def get_version(module): """ Attempts to read a version attribute from the given module that could be specified via several different names and formats. """ version_names = ["__version__", "get_version", "version"] version_names.extend([name.upper() for name in version_names]) for name in ve...
java
public static ComplexNumber Divide(ComplexNumber z1, double scalar) { return new ComplexNumber(z1.real / scalar, z1.imaginary / scalar); }
python
def create_pipeline(self): """Use JSON files to create Pipelines.""" pipelines = self.settings['pipeline']['pipeline_files'] self.log.info('Uploading manual Pipelines: %s', pipelines) lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir) for...
python
def _merge_fix(d): """Fixes keys that start with "&" and "-" d = { "&steve": 10, "-gary": 4 } result = { "steve": 10, "gary": 4 } """ if type(d) is dict: for key in d.keys(): if key[0] in ('&', '-'): ...
java
public static @Nonnull List<DetachedPlugin> getDetachedPlugins(@Nonnull VersionNumber since) { return getDetachedPlugins().stream() .filter(detachedPlugin -> !detachedPlugin.getSplitWhen().isOlderThan(since)) .collect(Collectors.toList()); }
python
def compare_dict(da, db): """ Compare differencs from two dicts """ sa = set(da.items()) sb = set(db.items()) diff = sa & sb return dict(sa - diff), dict(sb - diff)
java
public static String findManifestProperty( String propertyName ) { String result = null; InputStream is = null; try { is = ManifestUtils.class.getResourceAsStream( "/META-INF/MANIFEST.MF" ); Properties props = new Properties(); props.load( is ); result = findManifestProperty( props, propertyName ); ...
python
def write_uint64(self, value, little_endian=True): """ Pack the value as an unsigned integer and write 8 bytes to the stream. Args: value: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: the number of bytes writte...
java
@Nullable public String getFlashControlModeDescription() { int[] values = _directory.getIntArray(TagFlashControlMode); if (values == null) return null; if (values.length == 0) return null; StringBuilder sb = new StringBuilder(); switch (values[0...
java
public static SSLContext buildSSLContext(HttpClientConfig config) throws IOException, GeneralSecurityException { KeyManagerFactory kmf = null; if (isSslKeyManagerEnabled(config)) { kmf = getKeyManagerFactory(config.getKeyStorePath(), new StoreProperties(config.getKeyStorePassword(), config.getK...
java
@Route(method = HttpMethod.POST, uri = "/session/clear") public Result clear() { session().clear(); return redirect(router.getReverseRouteFor(this, "index")); }
java
public Observable<ServiceResponse<Iteration>> getIterationWithServiceResponseAsync(UUID projectId, UUID iterationId) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (iterationId == null) { throw ne...
python
def get_media_url(request, media_id): """Get media URL.""" media = Media.objects.get(id=media_id) return HttpResponse(media.url.name)
python
def as_fs(self): """ Returns the value of component encoded as formatted string. Inspect each character in value of component. Certain nonalpha characters pass thru without escaping into the result, but most retain escaping. :returns: Formatted string associated with co...
python
def getSiblings(self, textId, subreference): """ Retrieve the siblings of a textual node :param textId: CtsTextMetadata Identifier :param reference: CapitainsCtsPassage Reference :return: GetPrevNextUrn request response from the endpoint """ textId = "{}:{}".format(textI...
java
@Override public java.util.List<com.liferay.commerce.wish.list.model.CommerceWishList> getCommerceWishLists( int start, int end) { return _commerceWishListLocalService.getCommerceWishLists(start, end); }
python
def assignCurrentRecord(self, text): """ Assigns the current record from the inputed text. :param text | <str> """ if self.showTreePopup(): item = self._treePopupWidget.currentItem() if item: self._currentRecord = ite...
python
def get_countries_geo_zone_by_id(cls, countries_geo_zone_id, **kwargs): """Find CountriesGeoZone Return single instance of CountriesGeoZone by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread...
python
def _get_action_endpoint(action): """ Return the endpoint base on the view's action :param action: :return: """ _endpoint = None if is_method(action): if hasattr(action, "_rule_cache"): rc = action._rule_cache if rc: k = list(rc.keys())[0] ...
java
public static JCGLUsageHint usageHintFromGL( final int hint) { switch (hint) { case GL15.GL_DYNAMIC_COPY: return JCGLUsageHint.USAGE_DYNAMIC_COPY; case GL15.GL_DYNAMIC_DRAW: return JCGLUsageHint.USAGE_DYNAMIC_DRAW; case GL15.GL_DYNAMIC_READ: return JCGLUsageHint.USAGE...
java
public FieldInfo getCounterField() { KeyArea keyArea = this.getKeyArea(DBConstants.MAIN_KEY_AREA); if (keyArea != null) { BaseField fldID = keyArea.getKeyField(DBConstants.MAIN_KEY_FIELD).getField(DBConstants.FILE_KEY_AREA); if (fldID instanceof CounterField) ...
java
public Matrix4d translationRotateScaleMulAffine(Vector3fc translation, Quaterniondc quat, Vector3fc scale, Matrix4d m) { return translationRotateScaleMulA...
python
def on_key_pressed(self, event): """ likely to take in a set of parameters to treat as up, down, left, right, likely to actually be based on a joystick event... not sure yet """ return # TODO if event.keysym == "Up": self.manager...
python
def make_fpfList(options): """ aggregate default fpf values and user-defined fpf values where enrichment factor calculations will be attempted. :param options: SplitInput object :return defaults: list includes default fpf values & unique user-defined values """ user_values = options.fpf de...
java
public static <K, V> SortedSetMultimap<K, V> createSortedSetMultiValueMap(Comparator<V> comparator) { return (SortedSetMultimap<K, V>) MultimapBuilder.hashKeys().treeSetValues(comparator); }
python
def raise_for_error(status_code, message=None, errors=None): """Helper method to raise exceptions based on the status code of a response received back from Vault. :param status_code: Status code received in a response from Vault. :type status_code: int :param message: Optional message to include in a r...
java
private void readAssignmentBaselines(Project.Assignments.Assignment assignment, ResourceAssignment mpx) { for (Project.Assignments.Assignment.Baseline baseline : assignment.getBaseline()) { int number = NumberHelper.getInt(baseline.getNumber()); //baseline.getBCWP() //baseline...
java
@JsonIgnore public void setTag(String key, String value) { requireArgument(key != null && !key.trim().isEmpty(), "Tag key cannot be null."); requireArgument(!ReservedField.isReservedField(key), "Tag is a reserved tag name."); if (value == null || value.isEmpty()) { _tags.remove(k...
python
def merge_recs_headers(recs): ''' take a list of recs [rec1,rec2,rec3....], each rec is a dictionary. make sure that all recs have the same headers. ''' headers = [] for rec in recs: keys = list(rec.keys()) for key in keys: if key not in headers: heade...
python
def validate(self): """ validate: Makes sure single selection question is valid Args: None Returns: boolean indicating if single selection question is valid """ try: assert self.question_type == exercises.SINGLE_SELECTION, "Assumption Failed: Question should b...
python
def use_comparative_authorization_view(self): """Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view""" self._object_views['authorization'] = COMPARATIVE # self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked ...
java
public static String patientToLine(Patient patient, NaaccrContext context) throws NaaccrIOException { if (patient == null) throw new NaaccrIOException("Patient is required"); if (context == null) throw new NaaccrIOException("Context is required"); // it wouldn't be very ...
java
public void setNameConstraints(byte[] bytes) throws IOException { if (bytes == null) { ncBytes = null; nc = null; } else { ncBytes = bytes.clone(); nc = new NameConstraintsExtension(FALSE, bytes); } }
java
public static Object getProperty( final Object src, final String propertyName ) { if (src == null) { throw new IllegalArgumentException( "no source object specified" ); } if (propertyName == null) { throw ne...
java
int calculateReplicationFactor(List<HostToken> allHostTokens) { Map<Long, Integer> groups = new HashMap<>(); Set<HostToken> uniqueHostTokens = new HashSet<>(allHostTokens); String dataCenter = cpConfig.getLocalDataCenter(); if (dataCenter == null) { dataCenter = localRack.s...
java
@Override protected void writeRef(int value) throws IOException { if (SIZE < _offset + 16) flushBuffer(); _buffer[_offset++] = (byte) BC_REF; writeInt(value); }
python
def purge_content(self, account_id, urls): """Purges one or more URLs from the CDN edge nodes. :param int account_id: the CDN account ID from which content should be purged. :param urls: a string or a list of strings representing the CDN URLs ...
java
public synchronized int read(byte b[], int off, int len) throws IOException { int avail=_avail-_pos; if (avail <=0) { fill(); avail=_avail-_pos; } if (avail <=0) len=-1; else { len=(avail < len) ? avail : len; ...
java
@Override public void execute() throws BuildException { if (getHome() == null) throw new BuildException("Home isn't set"); try { ProcessController pc = ProcessController.getInstance(); int exitCode = pc.stop(getHome()); if (exitCode != 0) throw...
python
def cublasCher(handle, uplo, n, alpha, x, incx, A, lda): """ Rank-1 operation on Hermitian matrix. """ status = _libcublas.cublasCher_v2(handle, _CUBLAS_FILL_MODE[uplo], n, alpha, int(x), incx, int(A), lda) cublasCheckSt...
python
def get_project_version_by_name(self, project, version_name): """Get a version Resource by its name present on a project. :param project: ID or key of the project to get versions from :type project: str :param version_name: name of the version to search for :type version_name: s...
python
def interp_like(self, other, method='linear', assume_sorted=False, kwargs={}): """Interpolate this object onto the coordinates of another object, filling the out of range values with NaN. Parameters ---------- other : Dataset or DataArray Object w...
python
def attribute_rewrite_map(self): """ Example: long_name -> a_b :return: the rewrite map :rtype: dict """ rewrite_map = dict() token_rewrite_map = self.generate_attribute_token_rewrite_map() for attribute_name, type_instance in self.getmembers(): ...
java
public void add(LongDoubleVector other) { if (other instanceof LongDoubleUnsortedVector) { LongDoubleUnsortedVector vec = (LongDoubleUnsortedVector) other; for (int i=0; i<vec.top; i++) { this.add(vec.idx[i], vec.vals[i]); } } else { // TO...
java
public static void checkIndex(int index, int size) { if (size < 0) { throw new IllegalArgumentException("Negative size: " + size); } if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index out of bounds: size=" + size + ", index=" + index); } }
python
def _operatorOperands(tokenlist): "generator to extract operators and operands in pairs" it = iter(tokenlist) while 1: try: yield (it.next(), it.next()) except StopIteration: break
java
public void marshall(TimeoutConfig timeoutConfig, ProtocolMarshaller protocolMarshaller) { if (timeoutConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(timeoutConfig.getInProgressTimeoutInMinu...
java
Object cloneReset() throws CloneNotSupportedException { // this method exists to enable 100% test coverage final StrTokenizer cloned = new StrTokenizer(); if (this.chars != null) { cloned.chars = new char[this.chars.length]; for (int i = 0; i < this.chars.length; i++) { ...
python
def _pack(self, msg): """ Packages msg according to Scratch message specification (encodes and appends length prefix to msg). Credit to chalkmarrow from the scratch.mit.edu forums for the prefix encoding code. """ n = len(msg) a = array.array('c') a.app...
python
def dumpfile(item, path): ''' Dump an object to a file by path. Args: item (object): The object to serialize. path (str): The file path to save. Returns: None ''' with io.open(path, 'wb') as fd: fd.write(en(item))
java
public static String initCap(String str) { assertStringNotNull(str); if (is_Null_or_Empty(str)) { return str; } if (str.length() == 1) { return str.toUpperCase(); } final char chars[] = str.toCharArray(); chars[0] = Character.toUpperCase(ch...
java
@Nonnull public static ESuccess closeWithoutFlush (@Nullable @WillClose final AutoCloseable aCloseable) { if (aCloseable != null) { try { // close stream aCloseable.close (); return ESuccess.SUCCESS; } catch (final Exception ex) { if (!isKnownEOF...
python
def capture_insert_from_model(cls, table_name, record_id, *, exclude_fields=()): """ Create a fresh insert record from the current model state in the database. For read-write connected models, this will lead to the attempted creation of a corresponding object in Salesforce. Arg...
python
def _flatten_from_root(self, env): """ Flatten values from root down in to new view. """ nodes = env.components # Path through the znode graph from root ('') to env path = [nodes[:n] for n in xrange(len(nodes) + 1)] # Expand path and map it to the root ...
python
def get_by_contract(self, contract_hash): """ Look up a set of notifications by the contract they are associated with Args: contract_hash (UInt160 or str): hash of contract for notifications to be retreived Returns: list: a list of notifications """ ...
python
def create(cls, job_id, spider, workflow, results=None, logs=None, status=JobStatus.PENDING): """Create a new entry for a scheduled crawler job.""" obj = cls( job_id=job_id, spider=spider, workflow=workflow, results=results, logs...
java
public void softCloneNonPositionParameters(Rectangle rect) { if (rect.rotation != 0) this.rotation = rect.rotation; if (rect.backgroundColor != null) this.backgroundColor = rect.backgroundColor; if (rect.border != UNDEFINED) this.border = rect.border; if (useVariableBorders) this.useVariableBorders ...
java
public FutureData<DataSiftResult> stop(PylonRecordingId recordingId) { if (recordingId == null || recordingId.getId() == null || recordingId.getId().isEmpty()) { throw new IllegalArgumentException("A valid recording id is required to stop a recording"); } FutureData<DataSiftResult> f...
python
def lock_excl(self, timeout='default'): """Establish an exclusive lock to the resource. :param timeout: Absolute time period (in milliseconds) that a resource waits to get unlocked by the locking session before returning an error. (Defaults to self.timeou...
java
@Override public Set<String> findAllJobTypes() { return stream(collection.find().maxTime(500, TimeUnit.MILLISECONDS).spliterator(), false) .map(doc -> doc.getString(ID)) .collect(toSet()); }
java
@Override public java.util.concurrent.Future<GetQueueUrlResult> getQueueUrlAsync(String queueName, com.amazonaws.handlers.AsyncHandler<GetQueueUrlRequest, GetQueueUrlResult> asyncHandler) { return getQueueUrlAsync(new GetQueueUrlRequest().withQueueName(queueName), asyncHandler); }
python
def get_auth_token(cls): """ Return the authorization token :return: string """ if 'Authorization' not in f_request.headers: raise ValueError("Missing Authorization Bearer in headers") data = f_request.headers['Authorization'].encode('ascii', 'ignore') ...
java
public void setColumn(ColumnVector cv, int c) throws MatrixException { if ((c < 0) || (c >= nCols)) { throw new MatrixException(MatrixException.INVALID_INDEX); } if (nRows != cv.nRows) { throw new MatrixException( MatrixExceptio...
python
def format_response_data_type(self, response_data): """格式化返回的值为正确的类型 :param response_data: 返回的数据 """ if isinstance(response_data, list) and not isinstance( response_data, str ): return response_data int_match_str = "|".join(self.config["response_f...