A [mapping](https://docs.python.org/3/glossary.html#term-mapping) object where keys and values are strings that represent the process environment. For example, `environ['HOME']` is the pathname of your home directory (on some platforms), and is equivalent to `getenv(\"HOME\")` in C. This mapping is captured the first time the [`os`](https://docs.python.org/3/library/os.html#module-os) module is imported, typically during Python startup as part of processing `site.py`. Changes to the environment made after this time are not reflected in [`os.environ`](https://docs.python.org/3/library/os.html#os.environ), except for changes made by modifying [`os.environ`](https://docs.python.org/3/library/os.html#os.environ) directly. This mapping may be used to modify the environment as well as query the environment. [`putenv()`](https://docs.python.org/3/library/os.html#os.putenv) will be called automatically when the mapping is modified. On Unix, keys and values use [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding) and `'surrogateescape'` error handler. Use [`environb`](https://docs.python.org/3/library/os.html#os.environb) if you would like to use a different encoding. On Windows, the keys are converted to uppercase. This also applies when getting, setting, or deleting an item. For example, `environ['monty'] = 'python'` maps the key `'MONTY'` to the value `'python'`. **Note** Calling [`putenv()`](https://docs.python.org/3/library/os.html#os.putenv) directly does not change [`os.environ`](https://docs.python.org/3/library/os.html#os.environ), so it’s better to modify [`os.environ`](https://docs.python.org/3/library/os.html#os.environ). **Note** On some platforms, including FreeBSD and macOS, setting `environ` may cause memory leaks. Refer to the system documentation for `putenv()`. You can delete items in this mapping to unset environment variables. [`unsetenv()`](https://docs.python.org/3/library/os.html#os.unsetenv) will be called automatically when an item is deleted from [`os.environ`](https://docs.python.org/3/library/os.html#os.environ), and when one of the `pop()` or `clear()` methods is called. *Changed in version 3.9:* Updated to support [**PEP 584**](https://peps.python.org/pep-0584/)’s merge (`|`) and update (`|=`) operators."}
{"_id": 3, "title": "", "text": "On Python ≥ 3.5, use [`pathlib.Path.mkdir`](https://docs.python.org/library/pathlib.html#pathlib.Path.mkdir):
```python from pathlib import Path Path(\"/my/directory\").mkdir(parents=True, exist_ok=True)
```
For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:
Try [`os.path.exists`](https://docs.python.org/library/os.path.html#os.path.exists), and consider [`os.makedirs`](https://docs.python.org/library/os.html#os.makedirs) for the creation.
```python import os if not os.path.exists(directory): os.makedirs(directory)
```
As noted in comments and elsewhere, there's a race condition – if the directory is created between the `os.path.exists` and the `os.makedirs` calls, the `os.makedirs` will fail with an `OSError`. Unfortunately, blanket-catching `OSError` and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.
One option would be to trap the `OSError` and examine the embedded error code (see [Is there a cross-platform way of getting information from Python’s OSError](https://stackoverflow.com/questions/273698/is-there-a-cross-platform-way-of-getting-information-from-pythons-oserror)):
```python import os, errno
try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise
```
Alternatively, there could be a second `os.path.exists`, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.
Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.
Modern versions of Python improve this code quite a bit, both by exposing [`FileExistsError`](https://docs.python.org/3.3/library/exceptions.html?#FileExistsError) (in 3.3+)...
Create a new directory at this given path. If *mode* is given, it is combined with the process’s `umask` value to determine the file mode and access flags. If the path already exists, [`FileExistsError`](https://docs.python.org/3/library/exceptions.html#FileExistsError) is raised. If *parents* is true, any missing parents of this path are created as needed; they are created with the default permissions without taking *mode* into account (mimicking the POSIX `mkdir -p` command). If *parents* is false (the default), a missing parent raises [`FileNotFoundError`](https://docs.python.org/3/library/exceptions.html#FileNotFoundError). If *exist_ok* is false (the default), [`FileExistsError`](https://docs.python.org/3/library/exceptions.html#FileExistsError) is raised if the target directory already exists. If *exist_ok* is true, [`FileExistsError`](https://docs.python.org/3/library/exceptions.html#FileExistsError) will not be raised unless the given path already exists in the file system and is not a directory (same behavior as the POSIX `mkdir -p` command). *Changed in version 3.5:* The *exist_ok* parameter was added."}
{"_id": 6, "title": "", "text": "A **staticmethod** is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument.
A **classmethod**, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how `dict.fromkeys()`, a classmethod, returns an instance of the subclass when called on a subclass:
Transform a method into a class method. A class method receives the class as an implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:
The `@classmethod` form is a function [decorator](https://docs.python.org/3/glossary.html#term-decorator) – see [Function definitions](https://docs.python.org/3/reference/compound_stmts.html#function) for details. A class method can be called either on the class (such as `C.f()`) or on an instance (such as `C().f()`). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than C++ or Java static methods. If you want those, see [`staticmethod()`](https://docs.python.org/3/library/functions.html#staticmethod) in this section. For more information on class methods, see [The standard type hierarchy](https://docs.python.org/3/reference/datamodel.html#types). *Changed in version 3.9:* Class methods can now wrap other [descriptors](https://docs.python.org/3/glossary.html#term-descriptor) such as [`property()`](https://docs.python.org/3/library/functions.html#property). *Changed in version 3.10:* Class methods now inherit the method attributes (`__module__`, `__name__`, `__qualname__`, `__doc__` and `__annotations__`) and have a new `__wrapped__` attribute. *Changed in version 3.11:* Class methods can no longer wrap other [descriptors](https://docs.python.org/3/glossary.html#term-descriptor) such as [`property()`](https://docs.python.org/3/library/functions.html#property).
Transform a method into a static method. A static method does not receive an implicit first argument. To declare a static method, use this idiom:
class C: @staticmethoddef f(arg1, arg2, argN): ...
The @staticmethod form is a function decorator – see Function definitions for details. A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()). Moreover, the static method descriptor is also callable, so it can be used in the class definition (such as f()). Static methods in Python are similar to those found in Java or C++. Also, see classmethod() for a variant that is useful for creating alternate class constructors. Like all decorators, it is also possible to call staticmethod as a regular function and do something with its result. This is needed in some cases where you need a reference to a function from a class body and you want to avoid the automatic transformation to instance method. For these cases, use this idiom:
def regular_function(): ...
class C: method = staticmethod(regular_function)
For more information on static methods, see The standard type hierarchy. Changed in version 3.10: Static methods now inherit the method attributes (__module__, __name__, __qualname__, __doc__ and __annotations__), have a new __wrapped__ attribute, and are now callable as regular functions."}
{"_id": 9, "title": "", "text": "[`DataFrame.iterrows`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html#pandas-dataframe-iterrows) is a generator which yields both the index and row (as a Series):
```python import pandas as pd
df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]}) df = df.reset_index() # make sure indexes pair with number of rows
for index, row in df.iterrows(): print(row['c1'], row['c2'])
df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]}) df = df.reset_index() # make sure indexes pair with number of rows
for index, row in df.iterrows(): print(row['c1'], row['c2'])
```"}
{"_id": 11, "title": "", "text": "Iteration The behavior of basic iteration over pandas objects depends on the type. When iterating over a Series, it is regarded as array-like, and basic iteration produces the values. DataFrames follow the dict-like convention of iterating over the “keys” of the objects. In short, basic iteration (for i in object) produces: Series: values DataFrame: column labels pandas objects also have the dict-like items() method to iterate over the (key, value) pairs. To iterate over the rows of a DataFrame, you can use the following methods: iterrows(): Iterate over the rows of a DataFrame as (index, Series) pairs. This converts the rows to Series objects, which can change the dtypes and has some performance implications. itertuples(): Iterate over the rows of a DataFrame as namedtuples of the values. This is a lot faster than iterrows(), and is in most cases preferable to use to iterate over the values of a DataFrame. Warning Iterating through pandas objects is generally slow. In many cases, iterating manually over the rows is not needed and can be avoided with one of the following approaches: Look for a vectorized solution: many operations can be performed using built-in methods or NumPy functions, (boolean) indexing, … When you have a function that cannot work on the full DataFrame/Series at once, it is better to use apply() instead of iterating over the values. See the docs on function application. If you need to do iterative manipulations on the values but performance is important, consider writing the inner loop with cython or numba. See the enhancing performance section for some examples of this approach. Warning You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect!"}
{"_id": 12, "title": "", "text": "You can use a global variable within other functions by declaring it as `global` **within each function that assigns a value to it**:
```python globvar = 0
def set_globvar_to_one(): global globvar # Needed to modify global copy of globvar globvar = 1
def print_globvar(): print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one() print_globvar() # Prints 1
```
Since it's unclear whether `globvar = 1` is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the `global` keyword.
See other answers if you want to share a global variable across modules. "}
{"_id": 13, "title": "", "text": "```python globvar = 0
def set_globvar_to_one(): global globvar # Needed to modify global copy of globvar globvar = 1
def print_globvar(): print(globvar) # No need for global declaration to read value of globvar
set_globvar_to_one() print_globvar() # Prints 1
```"}
{"_id": 14, "title": "", "text": "7.12. The global statement global_stmt ::= \"global\" identifier (\",\" identifier)* The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global. Names listed in a global statement must not be used in the same code block textually preceding that global statement. Names listed in a global statement must not be defined as formal parameters, or as targets in with statements or except clauses, or in a for target list, class definition, function definition, import statement, or variable annotation. CPython implementation detail: The current implementation does not enforce some of these restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program. Programmer’s note: global is a directive to the parser. It applies only to code parsed at the same time as the global statement. In particular, a global statement contained in a string or code object supplied to the built-in exec() function does not affect the code block containing the function call, and code contained in such a string is unaffected by global statements in the code containing the function call. The same applies to the eval() and compile() functions."}
{"_id": 15, "title": "", "text": "[Decode the `bytes` object](https://docs.python.org/3/library/stdtypes.html#bytes.decode) to produce a string:
The above example *assumes* that the `bytes` object is in UTF-8, because it is a common encoding. However, you should use the encoding your data is actually in!"}
{"_id": 16, "title": "", "text": "```python >>> b\"abcde\".decode(\"utf-8\") 'abcde'
Return the bytes decoded to a [`str`](https://docs.python.org/3/library/stdtypes.html#str). *encoding* defaults to `'utf-8'`; see [Standard Encodings](https://docs.python.org/3/library/codecs.html#standard-encodings) for possible values. *errors* controls how decoding errors are handled. If `'strict'` (the default), a [`UnicodeError`](https://docs.python.org/3/library/exceptions.html#UnicodeError) exception is raised. Other possible values are `'ignore'`, `'replace'`, and any other name registered via [`codecs.register_error()`](https://docs.python.org/3/library/codecs.html#codecs.register_error). See [Error Handlers](https://docs.python.org/3/library/codecs.html#error-handlers) for details. For performance reasons, the value of *errors* is not checked for validity unless a decoding error actually occurs, [Python Development Mode](https://docs.python.org/3/library/devmode.html#devmode) is enabled or a [debug build](https://docs.python.org/3/using/configure.html#debug-build) is used. **Note** Passing the *encoding* argument to [`str`](https://docs.python.org/3/library/stdtypes.html#str) allows decoding any [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) directly, without needing to make a temporary `bytes` or `bytearray` object. *Changed in version 3.1:* Added support for keyword arguments. *Changed in version 3.9:* The value of the *errors* argument is now checked in [Python Development Mode](https://docs.python.org/3/library/devmode.html#devmode) and in [debug mode](https://docs.python.org/3/using/configure.html#debug-build)."}
{"_id": 18, "title": "", "text": "Use [`datetime`](https://docs.python.org/3/library/datetime.html):
To save typing, you can import the `datetime` object from the [`datetime`](https://docs.python.org/3/library/datetime.html) module:
```python >>> from datetime import datetime
```
Then remove the prefix `datetime.` from all of the above."}
{"_id": 19, "title": "", "text": "```python >>> import datetime >>> now = datetime.datetime.now() >>> now datetime.datetime(2009, 1, 6, 15, 8, 24, 78915) >>> print(now) 2009-01-06 15:08:24.789150
```"}
{"_id": 20, "title": "", "text": "datetime — Basic date and time types Source code: Lib/datetime.py The datetime module supplies classes for manipulating dates and times. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation. Aware and Naive Objects Date and time objects may be categorized as “aware” or “naive” depending on whether or not they include timezone information.
With sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information, an aware object can locate itself relative to other aware objects. An aware object represents a specific moment in time that is not open to interpretation. [1] A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it is up to the program whether a particular number represents metres, miles, or mass. Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality. For applications requiring aware objects, datetime and time objects have an optional time zone information attribute, tzinfo, that can be set to an instance of a subclass of the abstract tzinfo class. These tzinfo objects capture information about the offset from UTC time, the time zone name, and whether daylight saving time is in effect. Only one concrete tzinfo class, the timezone class, is supplied by the datetime module. The timezone class can represent simple timezones with fixed offsets from UTC, such as UTC itself or North American EST and EDT timezones. Supporting timezones at deeper levels of detail is up to the application. The rules for time adjustment across the world are more political than rational, change frequently, and there is no standard suitable for every application aside from UTC. Available Types class datetime.date An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes: year, month, and day.
class datetime.time An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds. (There is no notion of “leap seconds” here.) Attributes: hour, minute, second, microsecond, and tzinfo.
class datetime.datetime A combination of a date and a time. Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo."}
{"_id": 21, "title": "", "text": "From [Python Documentation](https://docs.python.org/3/tutorial/errors.html#handling-exceptions):
> An except clause may name multiple exceptions as a parenthesized tuple, for example >
```python except (IDontLikeYouException, YouAreBeingMeanException) as e: pass
Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using `as`."}
{"_id": 22, "title": "", "text": "```python except (IDontLikeYouException, YouAreBeingMeanException) as e: pass
```"}
{"_id": 23, "title": "", "text": "Handling Exceptions A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example: ... except (RuntimeError, TypeError, NameError): ... pass"}
{"_id": 24, "title": "", "text": "[`shutil`](http://docs.python.org/3/library/shutil.html) has many methods you can use. One of which is:
```python import shutil
shutil.copyfile(src, dst)
# 2nd option shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp
```
- Copy the contents of the file named `src` to a file named `dst`. Both `src` and `dst` need to be the entire filename of the files, including path. - The destination location must be writable; otherwise, an `IOError` exception will be raised. - If `dst` already exists, it will be replaced. - Special files such as character or block devices and pipes cannot be copied with this function. - With `copy`, `src` and `dst` are path names given as `str`s.
Another `shutil` method to look at is [`shutil.copy2()`](https://docs.python.org/3/library/shutil.html#shutil.copy2). It's similar but preserves more metadata (e.g. time stamps).
If you use `os.path` operations, use `copy` rather than `copyfile`. `copyfile` will only accept strings."}
{"_id": 25, "title": "", "text": "```python import shutil
shutil.copyfile(src, dst)
# 2nd option shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp
The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal. For operations on individual files, see also the os module. shutil.copyfile(src, dst, *, follow_symlinks=True) Copy the contents (no metadata) of the file named src to a file named dst and return dst in the most efficient way possible. src and dst are path-like objects or path names given as strings.
dst must be the complete target file name; look at copy() for a copy that accepts a target directory path. If src and dst specify the same file, SameFileError is raised.
The destination location must be writable; otherwise, an OSError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function.
If follow_symlinks is false and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to.
Raises an auditing event shutil.copyfile with arguments src, dst.
Changed in version 3.3: IOError used to be raised instead of OSError. Added follow_symlinks argument. Now returns dst.
Changed in version 3.4: Raise SameFileError instead of Error. Since the former is a subclass of the latter, this change is backward compatible.
Changed in version 3.8: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section."}
{"_id": 27, "title": "", "text": "Use the [`in` operator](https://docs.python.org/reference/expressions.html#membership-test-details):
```python if \"blah\" not in somestring: continue
```
Note: This is case-sensitive."}
{"_id": 28, "title": "", "text": "```python if \"blah\" not in somestring: continue
```"}
{"_id": 29, "title": "", "text": "6.10.2. Membership test operations The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s. All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).
For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so \"\" in \"abc\" will return True.
For user-defined classes which define the __contains__() method, x in y returns True if y.__contains__(x) returns a true value, and False otherwise.
For user-defined classes which do not define __contains__() but do define __iter__(), x in y is True if some value z, for which the expression x is z or x == z is true, is produced while iterating over y. If an exception is raised during the iteration, it is as if in raised that exception.
Lastly, the old-style iteration protocol is tried: if a class defines __getitem__(), x in y is True if and only if there is a non-negative integer index i such that x is y[i] or x == y[i], and no lower integer index raises the IndexError exception. (If any other exception is raised, it is as if in raised that exception).
The operator not in is defined to have the inverse truth value of in."}
{"_id": 30, "title": "", "text": "## Best practice
First, check if the file or folder exists and then delete it. You can achieve this in two ways:
1. `os.path.isfile(\"/path/to/file\")` 2. Use `exception handling.`
**EXAMPLE** for `os.path.isfile`
```python #!/usr/bin/python import os
myfile = \"/tmp/foo.txt\" # If file exists, delete it. if os.path.isfile(myfile): os.remove(myfile) else: # If it fails, inform the user. print(\"Error: %s file not found\" % myfile)
```
### Exception Handling
```python #!/usr/bin/python import os
# Get input. myfile = raw_input(\"Enter file name to delete: \")
# Try to delete the file. try: os.remove(myfile) except OSError as e: # If it fails, inform the user. print(\"Error: %s - %s.\" % (e.filename, e.strerror))
```
### Respective output
``` Enter file name to delete : demo.txt Error: demo.txt - No such file or directory.
Enter file name to delete : rrr.txt Error: rrr.txt - Operation not permitted.
Enter file name to delete : foo.txt
```
### Python syntax to delete a folder
```python shutil.rmtree()
```
Example for `shutil.rmtree()`
```python #!/usr/bin/python import os import sys import shutil
# Get directory name mydir = raw_input(\"Enter directory name: \")
# Try to remove the tree; if it fails, throw an error using try...except. try: shutil.rmtree(mydir) except OSError as e: print(\"Error: %s - %s.\" % (e.filename, e.strerror)) ```"}
{"_id": 31, "title": "", "text": "```python #!/usr/bin/python import os import sys import shutil
# Get directory name mydir = raw_input(\"Enter directory name: \")
# Try to remove the tree; if it fails, throw an error using try...except. try: shutil.rmtree(mydir) except OSError as e: print(\"Error: %s - %s.\" % (e.filename, e.strerror)) ```"}
{"_id": 32, "title": "", "text": "shutil.**rmtree**(*path*, *ignore_errors=False*, *onerror=None*, ***, *onexc=None*, *dir_fd=None*)
Delete an entire directory tree; *path* must point to a directory (but not a symbolic link to a directory). If *ignore_errors* is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by *onexc* or *onerror* or, if both are omitted, exceptions are propagated to the caller. This function can support [paths relative to directory descriptors](https://docs.python.org/3/library/os.html#dir-fd). **Note** On platforms that support the necessary fd-based functions a symlink attack resistant version of [`rmtree()`](https://docs.python.org/3/library/shutil.html#shutil.rmtree) is used by default. On other platforms, the [`rmtree()`](https://docs.python.org/3/library/shutil.html#shutil.rmtree) implementation is susceptible to a symlink attack: given proper timing and circumstances, attackers can manipulate symlinks on the filesystem to delete files they wouldn’t be able to access otherwise. Applications can use the [`rmtree.avoids_symlink_attacks`](https://docs.python.org/3/library/shutil.html#shutil.rmtree.avoids_symlink_attacks) function attribute to determine which case applies. If *onexc* is provided, it must be a callable that accepts three parameters: *function*, *path*, and *excinfo*. The first parameter, *function*, is the function which raised the exception; it depends on the platform and implementation. The second parameter, *path*, will be the path name passed to *function*. The third parameter, *excinfo*, is the exception that was raised. Exceptions raised by *onexc* will not be caught. The deprecated *onerror* is similar to *onexc*, except that the third parameter it receives is the tuple returned from [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info). Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `shutil.rmtree` with arguments `path`, `dir_fd`. *Changed in version 3.3:* Added a symlink attack resistant version that is used automatically if platform supports fd-based functions. *Changed in version 3.8:* On Windows, will no longer delete the contents of a directory junction before removing the junction. *Changed in version 3.11:* Added the *dir_fd* parameter. *Changed in version 3.12:* Added the *onexc* parameter, deprecated *onerror*."}
{"_id": 33, "title": "", "text": "```python if not a: print(\"List is empty\")
```
Using the [implicit booleanness](https://docs.python.org/library/stdtypes.html#truth-value-testing) of the empty `list` is quite Pythonic."}
{"_id": 34, "title": "", "text": "```python if not a: print(\"List is empty\")
```"}
{"_id": 35, "title": "", "text": "Built-in Types The following sections describe the standard types that are built into the interpreter.
The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions.
Some collection classes are mutable. The methods that add, subtract, or rearrange their members in place, and don’t return a specific item, never return the collection instance itself but None.
Some operations are supported by several object types; in particular, practically all objects can be compared for equality, tested for truth value, and converted to a string (with the repr() function or the slightly different str() function). The latter function is implicitly used when an object is written by the print() function.
Truth Value Testing Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.
By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. [1] Here are most of the built-in objects considered false:
constants defined to be false: None and False
zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
empty sequences and collections: '', (), [], {}, set(), range(0)
Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)
Boolean Operations — and, or, not These are the Boolean operations, ordered by ascending priority:
Operation
Result
Notes
x or y
if x is true, then x, else y
(1)
x and y
if x is false, then x, else y
(2)
not x
if x is false, then True, else False
(3)
Notes:
This is a short-circuit operator, so it only evaluates the second argument if the first one is false.
This is a short-circuit operator, so it only evaluates the second argument if the first one is true.
not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error."}
{"_id": 36, "title": "", "text": "If the reason you're checking is so you can do something like `if file_exists: open_it()`, it's safer to use a `try` around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.
If you're not planning to open the file immediately, you can use [`os.path.isfile`](https://docs.python.org/library/os.path.html#os.path.isfile) if you need to be sure it's a file.
> Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path. >
Return `True` if *path* is an [`existing`](https://docs.python.org/3/library/os.path.html#os.path.exists) regular file. This follows symbolic links, so both [`islink()`](https://docs.python.org/3/library/os.path.html#os.path.islink) and [`isfile()`](https://docs.python.org/3/library/os.path.html#os.path.isfile) can be true for the same path. *Changed in version 3.6:* Accepts a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object)."}
{"_id": 39, "title": "", "text": "Use the `+` operator to combine the lists:
```python listone = [1, 2, 3] listtwo = [4, 5, 6]
joinedlist = listone + listtwo
```
Output:
```python >>> joinedlist [1, 2, 3, 4, 5, 6]
```
NOTE: This will create a new list with a shallow copy of the items in the first list, followed by a shallow copy of the items in the second list. Use [copy.deepcopy()](https://docs.python.org/3/library/copy.html#copy.deepcopy) to get deep copies of lists."}
{"_id": 40, "title": "", "text": "```python listone = [1, 2, 3] listtwo = [4, 5, 6]
joinedlist = listone + listtwo
```
Output:
```python >>> joinedlist [1, 2, 3, 4, 5, 6]
```"}
{"_id": 41, "title": "", "text": "copy.**deepcopy**(*x*[, *memo*])Return a deep copy of *x*.
*exception* copy.**Error**Raised for module specific errors.
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
- A *shallow copy* constructs a new compound object and then (to the extent possible) inserts *references* into it to the objects found in the original. - A *deep copy* constructs a new compound object and then, recursively, inserts *copies* into it of the objects found in the original.
Two problems often exist with deep copy operations that don’t exist with shallow copy operations:
- Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop. - Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.
The [`deepcopy()`](https://docs.python.org/3/library/copy.html#copy.deepcopy) function avoids these problems by:
- keeping a `memo` dictionary of objects already copied during the current copying pass; and - letting user-defined classes override the copying operation or the set of components copied.
This module does not copy types like module, method, stack trace, stack frame, file, socket, window, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) module.
Shallow copies of dictionaries can be made using [`dict.copy()`](https://docs.python.org/3/library/stdtypes.html#dict.copy), and of lists by assigning a slice of the entire list, for example, `copied_list = original_list[:]`.
Classes can use the same interfaces to control copying that they use to control pickling. See the description of module [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) for information on these methods. In fact, the [`copy`](https://docs.python.org/3/library/copy.html#module-copy) module uses the registered pickle functions from the [`copyreg`](https://docs.python.org/3/library/copyreg.html#module-copyreg) module.
In order for a class to define its own copy implementation, it can define special methods `__copy__()` and `__deepcopy__()`. The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the `memo` dictionary. If the `__deepcopy__()` implementation needs to make a deep copy of a component, it should call the [`deepcopy()`](https://docs.python.org/3/library/copy.html#copy.deepcopy) function with the component as first argument and the memo dictionary as second argument. The memo dictionary should be treated as an opaque object.
**See also**
**Module [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle)**Discussion of the special methods used to support object state retrieval and restoration."}
{"_id": 42, "title": "", "text": "[`figure`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.figure.html) tells you the call signature:
```python from matplotlib.pyplot import figure
figure(figsize=(8, 6), dpi=80)
```
`figure(figsize=(1,1))` would create an inch-by-inch image, which would be 80-by-80 pixels unless you also give a different dpi argument."}
{"_id": 43, "title": "", "text": "```python from matplotlib.pyplot import figure
**matplotlib.pyplot.figure(*num=None*, *figsize=None*, *dpi=None*, ***, *facecolor=None*, *edgecolor=None*, *frameon=True*, *FigureClass=*, *clear=False*, ***kwargs*)[[source]](https://github.com/matplotlib/matplotlib/blob/v3.9.1/lib/matplotlib/pyplot.py#L870-L1056)**Create a new figure, or activate an existing figure."}
{"_id": 45, "title": "", "text": "There is also the [Python termcolor module](http://pypi.python.org/pypi/termcolor). Usage is pretty simple:
[`.extend()`](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) appends **multiple objects** that are taken from inside the specified iterable:
```python >>> x = [1, 2, 3] >>> x.extend([4, 5]) >>> print(x) [1, 2, 3, 4, 5] ```"}
{"_id": 50, "title": "", "text": "| s.append(x) | appends x to the end of the sequence (same as s[len(s):len(s)] = [x]) | | --- | --- |
| s.extend(t) or s += t | extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t) | | --- | --- |"}
{"_id": 51, "title": "", "text": "To get the full path to the directory a Python file is contained in, write this in that file:
```python import os dir_path = os.path.dirname(os.path.realpath(__file__))
```
(Note that the incantation above won't work if you've already used `os.chdir()` to change your current working directory, since the value of the `__file__` constant is relative to the current working directory and is not changed by an `os.chdir()` call.)
---
To get the current working directory use
```python import os cwd = os.getcwd()
```
---
Documentation references for the modules, constants and functions used above:
- The [`os`](https://docs.python.org/library/os.html) and [`os.path`](https://docs.python.org/library/os.path.html#module-os.path) modules. - The [`__file__`](https://docs.python.org/reference/datamodel.html) constant - [`os.path.realpath(path)`](https://docs.python.org/library/os.path.html#os.path.realpath) (returns *\"the canonical path of the specified filename, eliminating any symbolic links encountered in the path\"*) - [`os.path.dirname(path)`](https://docs.python.org/library/os.path.html#os.path.dirname) (returns *\"the directory name of pathname `path`\"*) - [`os.getcwd()`](https://docs.python.org/library/os.html#os.getcwd) (returns *\"a string representing the current working directory\"*) - [`os.chdir(path)`](https://docs.python.org/library/os.html#os.chdir) (*\"change the current working directory to `path`\"*)"}
{"_id": 52, "title": "", "text": "```python import os dir_path = os.path.dirname(os.path.realpath(__file__))
Return the directory name of pathname *path*. This is the first element of the pair returned by passing *path* to the function [`split()`](https://docs.python.org/3/library/os.path.html#os.path.split). *Changed in version 3.6:* Accepts a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object)."}
{"_id": 54, "title": "", "text": "## Rename Specific Columns
Use the [`df.rename()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html) function and refer the columns to be renamed. Not all the columns have to be renamed:
You can specify `errors='raise'` to raise errors if an invalid column-to-rename is specified."}
{"_id": 55, "title": "", "text": "```python df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
# Or rename the existing DataFrame (rather than creating a copy) df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)
**DataFrame.rename(*mapper=None*, ***, *index=None*, *columns=None*, *axis=None*, *copy=None*, *inplace=False*, *level=None*, *errors='ignore'*)[[source]](https://github.com/pandas-dev/pandas/blob/v2.2.2/pandas/core/frame.py#L5636-L5776)**Rename columns or index labels. Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error."}
{"_id": 57, "title": "", "text": "To delete a key regardless of whether it is in the dictionary, use the two-argument form of [`dict.pop()`](http://docs.python.org/library/stdtypes.html#dict.pop):
```python my_dict.pop('key', None)
```
This will return `my_dict[key]` if `key` exists in the dictionary, and `None` otherwise. If the second parameter is not specified (i.e. `my_dict.pop('key')`) and `key` does not exist, a `KeyError` is raised.
To delete a key that is guaranteed to exist, you can also use
```python del my_dict['key']
```
This will raise a `KeyError` if the key is not in the dictionary."}
{"_id": 58, "title": "", "text": "```python my_dict.pop('key', None)
If *key* is in the dictionary, remove it and return its value, else return *default*. If *default* is not given and *key* is not in the dictionary, a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) is raised."}
{"_id": 60, "title": "", "text": "The [`sorted()`](https://docs.python.org/library/functions.html#sorted) function takes a `key=` parameter
Alternatively, you can use [`operator.itemgetter`](https://docs.python.org/library/operator.html#operator.itemgetter) instead of defining the function yourself
```python from operator import itemgetter newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
```
For completeness, add `reverse=True` to sort in descending order
Return a new sorted list from the items in *iterable*. Has two optional arguments which must be specified as keyword arguments. *key* specifies a function of one argument that is used to extract a comparison key from each element in *iterable* (for example, `key=str.lower`). The default value is `None` (compare the elements directly). *reverse* is a boolean value. If set to `True`, then the list elements are sorted as if each comparison were reversed. Use [`functools.cmp_to_key()`](https://docs.python.org/3/library/functools.html#functools.cmp_to_key) to convert an old-style *cmp* function to a *key* function. The built-in [`sorted()`](https://docs.python.org/3/library/functions.html#sorted) function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade). The sort algorithm uses only `<` comparisons between items. While defining an [`__lt__()`](https://docs.python.org/3/reference/datamodel.html#object.__lt__) method will suffice for sorting, [**PEP 8**](https://peps.python.org/pep-0008/) recommends that all six [rich comparisons](https://docs.python.org/3/reference/expressions.html#comparisons) be implemented. This will help avoid bugs when using the same data with other ordering tools such as [`max()`](https://docs.python.org/3/library/functions.html#max) that rely on a different underlying method. Implementing all six comparisons also helps avoid confusion for mixed type comparisons which can call reflected the [`__gt__()`](https://docs.python.org/3/reference/datamodel.html#object.__gt__) method. For sorting examples and a brief sorting tutorial, see [Sorting Techniques](https://docs.python.org/3/howto/sorting.html#sortinghowto)."}
{"_id": 63, "title": "", "text": "[`in`](https://docs.python.org/reference/expressions.html#membership-test-operations) tests for the existence of a key in a [`dict`](https://docs.python.org/library/stdtypes.html#dict):
```python d = {\"key1\": 10, \"key2\": 23}
if \"key1\" in d: print(\"this will execute\")
if \"nonexistent key\" in d: print(\"this will not\")
```
---
Use [`dict.get()`](https://docs.python.org/library/stdtypes.html#dict.get) to provide a default value when the key does not exist:
```python d = {}
for i in range(100): key = i % 10 d[key] = d.get(key, 0) + 1
```
---
To provide a default value for *every* key, either use [`dict.setdefault()`](https://docs.python.org/library/stdtypes.html#dict.setdefault) on each assignment:
```python d = {}
for i in range(100): d[i % 10] = d.setdefault(i % 10, 0) + 1
```
...or better, use [`defaultdict`](https://docs.python.org/library/collections.html#collections.defaultdict) from the [`collections`](https://docs.python.org/library/collections.html) module:
```python from collections import defaultdict
d = defaultdict(int)
for i in range(100): d[i % 10] += 1 ```"}
{"_id": 64, "title": "", "text": "```python d = {}
for i in range(100): key = i % 10 d[key] = d.get(key, 0) + 1
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError)."}
{"_id": 66, "title": "", "text": "Use [`random.choice()`](https://docs.python.org/library/random.html#random.choice):
For [cryptographically secure](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator) random choices (e.g., for generating a passphrase from a wordlist), use [`secrets.choice()`](https://docs.python.org/library/secrets.html#secrets.choice):
`secrets` is new in Python 3.6. On older versions of Python you can use the [`random.SystemRandom`](https://docs.python.org/library/random.html#random.SystemRandom) class:
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError)."}
{"_id": 69, "title": "", "text": "The best way to do this in Pandas is to use [`drop`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html):
```python df = df.drop('column_name', axis=1)
```
where `1` is the *axis* number (`0` for rows and `1` for columns.)
Or, the `drop()` method accepts `index`/`columns` keywords as an alternative to specifying the axis. So we can now just do:
- *This was [introduced in v0.21.0](https://pandas.pydata.org/pandas-docs/stable/whatsnew/v0.21.0.html#method-drop-now-also-accepts-index-columns-keywords) (October 27, 2017)*
To delete the column without having to reassign `df` you can do:
**DataFrame.drop(*labels=None*, ***, *axis=0*, *index=None*, *columns=None*, *level=None*, *inplace=False*, *errors='raise'*)[[source]](https://github.com/pandas-dev/pandas/blob/v2.2.2/pandas/core/frame.py#L5433-L5589)**Drop specified labels from rows or columns. Remove rows or columns by specifying label names and corresponding axis, or by directly specifying index or column names. When using a multi-index, labels on different levels can be removed by specifying the level. See the [user guide](https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced-shown-levels) for more information about the now unused levels."}
{"_id": 72, "title": "", "text": "Use [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) if you are using Python 2.7 or 3.x and you want the number of occurrences for each element:
A [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) is a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) subclass for counting [hashable](https://docs.python.org/3/glossary.html#term-hashable) objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) class is similar to bags or multisets in other languages. Elements are counted from an *iterable* or initialized from another *mapping* (or counter):~~>>>~~
`c = Counter() *# a new, empty counter*c = Counter('gallahad') *# a new counter from an iterable*c = Counter({'red': 4, 'blue': 2}) *# a new counter from a mapping*c = Counter(cats=4, dogs=8) *# a new counter from keyword args*` Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError):~~>>>~~
`c = Counter(['eggs', 'ham']) c['bacon'] *# count of a missing element is zero*` Setting a count to zero does not remove an element from a counter. Use `del` to remove it entirely:~~>>>~~
`c['sausage'] = 0 *# counter entry with a zero count***del** c['sausage'] *# del actually removes the entry*` *Added in version 3.1.* *Changed in version 3.7:* As a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) subclass, [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) inherited the capability to remember insertion order. Math operations on *Counter* objects also preserve order. Results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand."}
{"_id": 75, "title": "", "text": "Set the mode in [`open()`](https://docs.python.org/3/library/functions.html#open) to `\"a\"` (append) instead of `\"w\"` (write):
```python with open(\"test.txt\", \"a\") as myfile: myfile.write(\"appended text\")
```
The [documentation](https://docs.python.org/3/library/functions.html#open) lists all the available modes."}
{"_id": 76, "title": "", "text": "```python with open(\"test.txt\", \"a\") as myfile: myfile.write(\"appended text\")
Open *file* and return a corresponding [file object](https://docs.python.org/3/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) is raised. See [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#tut-files) for more examples of how to use this function. *file* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.) *mode* is an optional string that specifies the mode in which the file is opened. It defaults to `'r'` which means open for reading in text mode. Other common values are `'w'` for writing (truncating the file if it already exists), `'x'` for exclusive creation, and `'a'` for appending (which on *some* Unix systems, means that *all* writes append to the end of the file regardless of the current seek position). In text mode, if *encoding* is not specified the encoding used is platform-dependent: [`locale.getencoding()`](https://docs.python.org/3/library/locale.html#locale.getencoding) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave *encoding* unspecified.)"}
{"_id": 78, "title": "", "text": "Try the method `rstrip()` (see doc [Python 2](http://docs.python.org/2/library/stdtypes.html#str.rstrip) and [Python 3](https://docs.python.org/3/library/stdtypes.html#str.rstrip))
Python's `rstrip()` method strips *all* kinds of trailing whitespace by default, not just one newline as Perl does with [`chomp`](http://perldoc.perl.org/functions/chomp.html).
```"}
{"_id": 80, "title": "", "text": "bytes.strip([chars]) bytearray.strip([chars]) Return a copy of the sequence with specified leading and trailing bytes removed. The chars argument is a binary sequence specifying the set of byte values to be removed - the name refers to the fact this method is usually used with ASCII characters. If omitted or None, the chars argument defaults to removing ASCII whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> >>> b' spacious '.strip() b'spacious' >>> b'www.example.com'.strip(b'cmowz.') b'example' The binary sequence of byte values to remove may be any bytes-like object. Note
The bytearray version of this method does not operate in place - it always produces a new object, even if no changes were made. The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do not operate in place, and instead produce new objects."}
{"_id": 81, "title": "", "text": "For non-negative (unsigned) integers only, use [`isdigit()`](https://docs.python.org/3/library/stdtypes.html#str.isdigit):
```python >>> a = \"03523\" >>> a.isdigit() True >>> b = \"963spam\" >>> b.isdigit() False
```
---
Documentation for `isdigit()`: [Python2](https://docs.python.org/2/library/stdtypes.html#str.isdigit), [Python3](https://docs.python.org/3/library/stdtypes.html#str.isdigit)
For Python 2 Unicode strings: [`isnumeric()`](https://docs.python.org/2/library/stdtypes.html#unicode.isnumeric)."}
{"_id": 82, "title": "", "text": "```python >>> a = \"03523\" >>> a.isdigit() True >>> b = \"963spam\" >>> b.isdigit() False
Return `True` if all characters in the string are digits and there is at least one character, `False` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal."}
{"_id": 84, "title": "", "text": "Use the `indent=` parameter of [`json.dump()`](https://docs.python.org/3/library/json.html#json.dump) or [`json.dumps()`](https://docs.python.org/3/library/json.html#json.dumps) to specify how many spaces to indent by:
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table). If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), [`float`](https://docs.python.org/3/library/functions.html#float), [`bool`](https://docs.python.org/3/library/functions.html#bool), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError). The [`json`](https://docs.python.org/3/library/json.html#module-json) module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str) objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes) objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str) input. If *ensure_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure_ascii* is false, these characters will be output as-is. If *check_circular* is false (default: `True`), then the circular reference check for container types will be skipped and a circular reference will result in a [`RecursionError`](https://docs.python.org/3/library/exceptions.html#RecursionError) (or worse). If *allow_nan* is false (default: `True`), then it will be a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) to serialize out of range [`float`](https://docs.python.org/3/library/functions.html#float) values (`nan`, `inf`, `-inf`) in strict compliance of the JSON specification. If *allow_nan* is true, their JavaScript equivalents (`NaN`, `Infinity`, `-Infinity`) will be used. If *indent* is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or `\"\"` will only insert newlines. `None` (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If *indent* is a string (such as `\"\\t\"`), that string is used to indent each level. *Changed in version 3.2:* Allow strings for *indent* in addition to integers. If specified, *separators* should be an `(item_separator, key_separator)` tuple. The default is `(', ', ': ')` if *indent* is `None` and `(',', ': ')` otherwise. To get the most compact JSON representation, you should specify `(',', ':')` to eliminate whitespace. *Changed in version 3.4:* Use `(',', ': ')` as default if *indent* is not `None`. If specified, *default* should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError). If not specified, [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) is raised. If *sort_keys* is true (default: `False`), then the output of dictionaries will be sorted by key. To use a custom [`JSONEncoder`](https://docs.python.org/3/library/json.html#json.JSONEncoder) subclass (e.g. one that overrides the [`default()`](https://docs.python.org/3/library/json.html#json.JSONEncoder.default) method to serialize additional types), specify it with the *cls* kwarg; otherwise [`JSONEncoder`](https://docs.python.org/3/library/json.html#json.JSONEncoder) is used. *Changed in version 3.6:* All optional parameters are now [keyword-only](https://docs.python.org/3/glossary.html#keyword-only-parameter). **Note** Unlike [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) and [`marshal`](https://docs.python.org/3/library/marshal.html#module-marshal), JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to [`dump()`](https://docs.python.org/3/library/json.html#json.dump) using the same *fp* will result in an invalid JSON file."}
{"_id": 87, "title": "", "text": "Use [`isinstance`](https://docs.python.org/library/functions.html#isinstance) to check if `o` is an instance of `str` or any subclass of `str`:
```python if isinstance(o, str):
```
To check if the type of `o` is exactly `str`, *excluding subclasses of `str`*:
```python if type(o) is str:
```
See [Built-in Functions](http://docs.python.org/library/functions.html) in the Python Library Reference for relevant information.
---
### Checking for strings in Python 2
For Python 2, this is a better way to check if `o` is a string:
```python if isinstance(o, basestring):
```
because this will also catch Unicode strings. [`unicode`](https://docs.python.org/2/library/functions.html#unicode) is not a subclass of `str`; both `str` and `unicode` are subclasses of [`basestring`](https://docs.python.org/2/library/functions.html#basestring). In Python 3, `basestring` no longer exists since there's [a strict separation](https://docs.python.org/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit) of strings ([`str`](https://docs.python.org/3/library/functions.html#func-str)) and binary data ([`bytes`](https://docs.python.org/3/library/functions.html#func-bytes)).
Alternatively, `isinstance` accepts a tuple of classes. This will return `True` if `o` is an instance of any subclass of any of `(str, unicode)`:
```python if isinstance(o, (str, unicode)): ```"}
{"_id": 88, "title": "", "text": "```python if isinstance(o, str):
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) exception is raised. [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) may not be raised for an invalid type if an earlier check succeeds. *Changed in version 3.10: classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union)."}
{"_id": 90, "title": "", "text": "When using [`matplotlib.pyplot.savefig`](https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.savefig.html), the file format can be specified by the extension:
```python from matplotlib import pyplot as plt
plt.savefig('foo.png') plt.savefig('foo.pdf')
```
That gives a rasterized or vectorized output respectively. In addition, there is sometimes undesirable whitespace around the image, which can be removed with:
Note that if showing the plot, `plt.show()` should follow `plt.savefig()`; otherwise, the file image will be blank."}
{"_id": 91, "title": "", "text": "```python from matplotlib import pyplot as plt
**matplotlib.pyplot.savefig(**args*, ***kwargs*)[[source]](https://github.com/matplotlib/matplotlib/blob/v3.9.1/lib/matplotlib/pyplot.py#L1223-L1230)**Save the current figure as an image or vector graphic to a file. Call signature:
The available output formats depend on the backend being used.**Parameters:fnamestr or path-like or binary file-like**A path, or a Python file-like object, or possibly some backend-dependent object such as [**`matplotlib.backends.backend_pdf.PdfPages`**](https://matplotlib.org/stable/api/backend_pdf_api.html#matplotlib.backends.backend_pdf.PdfPages). If *format* is set, it determines the output format, and the file is saved as *fname*. Note that *fname* is used verbatim, and there is no attempt to make the extension, if any, of *fname* match *format*, and no extension is appended. If *format* is not set, then the format is inferred from the extension of *fname*, if there is one. If *format* is not set and *fname* has no extension, then the file is saved with [`rcParams[\"savefig.format\"]`](https://matplotlib.org/stable/users/explain/customizing.html?highlight=savefig.format#matplotlibrc-sample) (default: `'png'`) and the appropriate extension is appended to *fname*."}
{"_id": 93, "title": "", "text": "### Python 3.4+
Use [`pathlib.Path.stem`](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.stem)
Use [`os.path.splitext`](https://docs.python.org/3/library/os.path.html#os.path.splitext) in combination with [`os.path.basename`](https://docs.python.org/3/library/os.path.html#os.path.basename):
Return `True` if *path* is an [`existing`](https://docs.python.org/dev/library/os.path.html#os.path.exists) directory. This follows symbolic links, so both [`islink()`](https://docs.python.org/dev/library/os.path.html#os.path.islink) and [`isdir()`](https://docs.python.org/dev/library/os.path.html#os.path.isdir) can be true for the same path. *Changed in version 3.6:* Accepts a [path-like object](https://docs.python.org/dev/glossary.html#term-path-like-object)."}
{"_id": 99, "title": "", "text": "[`os.rename()`](http://docs.python.org/library/os.html#os.rename), [`os.replace()`](https://docs.python.org/library/os.html#os.replace), or [`shutil.move()`](http://docs.python.org/library/shutil.html#shutil.move)
- The filename (`\"file.foo\"`) must be included in both the source and destination arguments. If it differs between the two, the file will be renamed as well as moved. - The directory within which the new file is being created must already exist. - On Windows, a file with that name must not exist or an exception will be raised, but `os.replace()` will silently replace a file even in that occurrence. - `shutil.move` simply calls `os.rename` in most cases. However, if the destination is on a different disk than the source, it will instead copy and then delete the source file."}
{"_id": 100, "title": "", "text": "```python import os import shutil
Rename the file or directory *src* to *dst*. If *dst* is a non-empty directory, [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) will be raised. If *dst* exists and is a file, it will be replaced silently if the user has permission. The operation may fail if *src* and *dst* are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). This function can support specifying *src_dir_fd* and/or *dst_dir_fd* to supply [paths relative to directory descriptors](https://docs.python.org/3/library/os.html#dir-fd). Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.rename` with arguments `src`, `dst`, `src_dir_fd`, `dst_dir_fd`. *Added in version 3.3.* *Changed in version 3.6:* Accepts a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) for *src* and *dst*."}
{"_id": 102, "title": "", "text": "The `property()` function returns a special [descriptor object](https://docs.python.org/howto/descriptor.html):
so `foo` the function is replaced by `property(foo)`, which we saw above is a special object. Then when you use `@foo.setter()`, what you are doing is call that `property().setter` method I showed you above, which returns a new copy of the property, but this time with the setter function replaced with the decorated method."}
{"_id": 103, "title": "", "text": "```python @property def foo(self): return self._foo
Return a property attribute. *fget* is a function for getting an attribute value. *fset* is a function for setting an attribute value. *fdel* is a function for deleting an attribute value. And *doc* creates a docstring for the attribute. A typical use is to define a managed attribute `x`:
x = property(getx, setx, delx, \"I'm the 'x' property.\")`
If *c* is an instance of *C*, `c.x` will invoke the getter, `c.x = value` will invoke the setter, and `del c.x` the deleter. If given, *doc* will be the docstring of the property attribute. Otherwise, the property will copy *fget*’s docstring (if it exists). This makes it possible to create read-only properties easily using [`property()`](https://docs.python.org/3/library/functions.html#property) as a [decorator](https://docs.python.org/3/glossary.html#term-decorator):
@property**def** voltage(self): *\"\"\"Get the current voltage.\"\"\"***return** self._voltage`
The `@property` decorator turns the `voltage()` method into a “getter” for a read-only attribute with the same name, and it sets the docstring for *voltage* to “Get the current voltage.”@**getter**@**setter**@**deleter**A property object has `getter`, `setter`, and `deleter` methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function. This is best explained with an example:
This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (`x` in this case.) The returned property object also has the attributes `fget`, `fset`, and `fdel` corresponding to the constructor arguments. *Changed in version 3.5:* The docstrings of property objects are now writeable."}
{"_id": 105, "title": "", "text": "For URL query parameters, use `request.args`.
For JSON posted with content type `application/json`, use [`request.get_json()`](https://flask.palletsprojects.com/api/#flask.Request.get_json).
```python data = request.get_json() ```"}
{"_id": 106, "title": "", "text": "```python data = request.get_json() ```"}
{"_id": 107, "title": "", "text": "get_json(force=False, silent=False, cache=True) Parse data as JSON.
If the mimetype does not indicate JSON (application/json, see is_json), or parsing fails, on_json_loading_failed() is called and its return value is used as the return value. By default this raises a 415 Unsupported Media Type resp.
Parameters: force (bool) – Ignore the mimetype and always try to parse JSON.
silent (bool) – Silence mimetype and parsing errors, and return None instead.
cache (bool) – Store the parsed JSON to return for subsequent calls.
Return type: Any | None
Changelog Changed in version 2.3: Raise a 415 error instead of 400.
Changed in version 2.1: Raise a 400 error if the content type is incorrect."}
{"_id": 108, "title": "", "text": "Use [`TestCase.assertRaises`](http://docs.python.org/library/unittest.html#unittest.TestCase.assertRaises) from the `unittest` module, for example:
Test that an exception is raised when *callable* is called with any positional or keyword arguments that are also passed to [`assertRaises()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises). The test passes if *exception* is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as *exception*. If only the *exception* and possibly the *msg* arguments are given, return a context manager so that the code under test can be written inline rather than as a function:
When used as a context manager, [`assertRaises()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises) accepts the additional keyword argument *msg*. The context manager will store the caught exception object in its `exception` attribute. This can be useful if the intention is to perform additional checks on the exception raised:
*Changed in version 3.1:* Added the ability to use [`assertRaises()`](https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises) as a context manager. *Changed in version 3.2:* Added the `exception` attribute. *Changed in version 3.3:* Added the *msg* keyword argument when used as a context manager."}
{"_id": 111, "title": "", "text": "You can use a [`timedelta`](http://docs.python.org/library/datetime.html#timedelta-objects) object:
```python from datetime import datetime, timedelta
d = datetime.today() - timedelta(days=days_to_subtract) ```"}
{"_id": 112, "title": "", "text": "```python from datetime import datetime, timedelta
A [`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object represents a duration, the difference between two [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) or [`date`](https://docs.python.org/3/library/datetime.html#datetime.date) instances.
*class* datetime.**timedelta**(*days=0*, *seconds=0*, *microseconds=0*, *milliseconds=0*, *minutes=0*, *hours=0*, *weeks=0*)All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative. Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units: • A millisecond is converted to 1000 microseconds. • A minute is converted to 60 seconds. • An hour is converted to 3600 seconds. • A week is converted to 7 days. and days, seconds and microseconds are then normalized so that the representation is unique, with • `0 <= microseconds < 1000000` • `0 <= seconds < 3600*24` (the number of seconds in one day) • `-999999999 <= days <= 999999999` The following example illustrates how any arguments besides *days*, *seconds* and *microseconds* are “merged” and normalized into those three resulting attributes:~~>>>~~
If any argument is a float and there are fractional microseconds, the fractional microseconds left over from all arguments are combined and their sum is rounded to the nearest microsecond using round-half-to-even tiebreaker. If no argument is a float, the conversion and normalization processes are exact (no information is lost). If the normalized value of days lies outside the indicated range, [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError) is raised. Note that normalization of negative values may be surprising at first. For example:~~>>>~~
Open *url*, which can be either a string containing a valid, properly encoded URL, or a [`Request`](https://docs.python.org/3/library/urllib.request.html#urllib.request.Request) object. *data* must be an object specifying additional data to be sent to the server, or `None` if no such data is needed. See [`Request`](https://docs.python.org/3/library/urllib.request.html#urllib.request.Request) for details. urllib.request module uses HTTP/1.1 and includes `Connection:close` header in its HTTP requests. The optional *timeout* parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS and FTP connections. If *context* is specified, it must be a [`ssl.SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext) instance describing the various SSL options. See [`HTTPSConnection`](https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection) for more details. The optional *cafile* and *capath* parameters specify a set of trusted CA certificates for HTTPS requests. *cafile* should point to a single file containing a bundle of CA certificates, whereas *capath* should point to a directory of hashed certificate files. More information can be found in [`ssl.SSLContext.load_verify_locations()`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_verify_locations). The *cadefault* parameter is ignored. This function always returns an object which can work as a [context manager](https://docs.python.org/3/glossary.html#term-context-manager) and has the properties *url*, *headers*, and *status*. See [`urllib.response.addinfourl`](https://docs.python.org/3/library/urllib.request.html#urllib.response.addinfourl) for more detail on these properties. For HTTP and HTTPS URLs, this function returns a [`http.client.HTTPResponse`](https://docs.python.org/3/library/http.client.html#http.client.HTTPResponse) object slightly modified. In addition to the three new methods above, the msg attribute contains the same information as the [`reason`](https://docs.python.org/3/library/http.client.html#http.client.HTTPResponse.reason) attribute — the reason phrase returned by server — instead of the response headers as it is specified in the documentation for [`HTTPResponse`](https://docs.python.org/3/library/http.client.html#http.client.HTTPResponse). For FTP, file, and data URLs and requests explicitly handled by legacy [`URLopener`](https://docs.python.org/3/library/urllib.request.html#urllib.request.URLopener) and [`FancyURLopener`](https://docs.python.org/3/library/urllib.request.html#urllib.request.FancyURLopener) classes, this function returns a [`urllib.response.addinfourl`](https://docs.python.org/3/library/urllib.request.html#urllib.response.addinfourl) object. Raises [`URLError`](https://docs.python.org/3/library/urllib.error.html#urllib.error.URLError) on protocol errors. Note that `None` may be returned if no handler handles the request (though the default installed global [`OpenerDirector`](https://docs.python.org/3/library/urllib.request.html#urllib.request.OpenerDirector) uses [`UnknownHandler`](https://docs.python.org/3/library/urllib.request.html#urllib.request.UnknownHandler) to ensure this never happens). In addition, if proxy settings are detected (for example, when a `*_proxy` environment variable like `http_proxy` is set), [`ProxyHandler`](https://docs.python.org/3/library/urllib.request.html#urllib.request.ProxyHandler) is default installed and makes sure the requests are handled through the proxy. The legacy `urllib.urlopen` function from Python 2.6 and earlier has been discontinued; [`urllib.request.urlopen()`](https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen) corresponds to the old `urllib2.urlopen`. Proxy handling, which was done by passing a dictionary parameter to `urllib.urlopen`, can be obtained by using [`ProxyHandler`](https://docs.python.org/3/library/urllib.request.html#urllib.request.ProxyHandler) objects.
The default opener raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `urllib.Request` with arguments `fullurl`, `data`, `headers`, `method` taken from the request object."}
{"_id": 117, "title": "", "text": "To delimit by a tab you can use the `sep` argument of [`to_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html):
```python df.to_csv(file_name, sep='\\t')
```
To use a specific encoding (e.g. 'utf-8') use the `encoding` argument:
```"}
{"_id": 119, "title": "", "text": "pandas.DataFrame.to_csv **DataFrame.to_csv(path_or_buf=None, ***, sep=',', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression='infer', quoting=None, quotechar='\"', lineterminator=None, chunksize=None, date_format=None, doublequote=True, escapechar=None, decimal='.', errors='strict', storage_options=None)[source]**Write object to a comma-separated values (csv) file."}
{"_id": 120, "title": "", "text": "This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.
To put this another way, there are two instances where null checking comes up:
1. Where null is a valid response in terms of the contract; and 2. Where it isn't a valid response.
(2) is easy. As of Java 1.7 you can use [`Objects.requireNonNull(foo)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Objects.html#requireNonNull(T)). (If you are stuck with a previous version then [`assert`ions](https://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html) may be a good alternative.)
\"Proper\" usage of this method would be like below. The method returns the object passed into it and throws a `NullPointerException` if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.
```java public Foo(Bar bar) { this.bar = Objects.requireNonNull(bar); }
```
It can also be used like an `assert`ion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.
```java Objects.requireNonNull(someobject, \"if someobject is null then something is wrong\"); someobject.doCalc();
```
Generally throwing a specific exception like `NullPointerException` when a value is null but shouldn't be is favorable to throwing a more general exception like `AssertionError`. This is the approach the Java library takes; favoring `NullPointerException` over `IllegalArgumentException` when an argument is not allowed to be null.
(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.
If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.
With non-collections it might be harder. Consider this as an example: if you have these interfaces:
```java public interface Action { void doSomething(); }
public interface Parser { Action findAction(String userInput); }
```
where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.
An alternative solution is to never return null and instead use the [Null Object pattern](https://en.wikipedia.org/wiki/Null_Object_pattern):
```java public class MyParser implements Parser { private static Action DO_NOTHING = new Action() { public void doSomething() { /* do nothing */ } };
public Action findAction(String userInput) { // ... if ( /* we can't find any actions */ ) { return DO_NOTHING; } } }
```
Compare:
```java Parser parser = ParserFactory.getParser(); if (parser == null) { // now what? // this would be an example of where null isn't (or shouldn't be) a valid response } Action action = parser.findAction(someInput); if (action == null) { // do nothing } else { action.doSomething(); }
which is a much better design because it leads to more concise code.
That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.
Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.
```java public Action findAction(final String userInput) { /* Code to return requested Action if found */ return new Action() { public void doSomething() { userConsole.err(\"Action not found: \" + userInput); } } } ```"}
{"_id": 121, "title": "", "text": "```java public Foo(Bar bar) { this.bar = Objects.requireNonNull(bar); } ```"}
{"_id": 122, "title": "", "text": "- requireNonNull
public static T requireNonNull(T obj)
Checks that the specified object reference is not `null`. This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated below:
**Type Parameters:**`T` - the type of the reference**Parameters:**`obj` - the object reference to check for nullity**Returns:**`obj` if not `null`**Throws:**[`NullPointerException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/NullPointerException.html) - if `obj` is `null`"}
{"_id": 123, "title": "", "text": "`==` tests for reference equality (whether they are the same object).
`.equals()` tests for value equality (whether they contain the same data).
[Objects.equals()](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#equals(java.lang.Object,%20java.lang.Object)) checks for `null` before calling `.equals()` so you don't have to (available as of JDK7, also available in [Guava](https://github.com/google/guava/wiki/CommonObjectUtilitiesExplained#equals)).
Consequently, if you want to test whether two strings have the same value you will probably want to use `Objects.equals()`.
```java // These two have the same value new String(\"test\").equals(\"test\") // --> true
// ... but they are not the same object new String(\"test\") == \"test\" // --> false
// ... neither are these new String(\"test\") == new String(\"test\") // --> false
// ... but these are because literals are interned by // the compiler and thus refer to the same object \"test\" == \"test\" // --> true
// ... string literals are concatenated by the compiler // and the results are interned. \"test\" == \"te\" + \"st\" // --> true
// ... but you should really just call Objects.equals() Objects.equals(\"test\", new String(\"test\")) // --> true Objects.equals(null, \"test\") // --> false Objects.equals(null, null) // --> true
```
From the Java Language Specification [JLS 15.21.3. Reference Equality Operators `==` and `!=`](https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html#jls-15.21.3):
> While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters (§3.10.5, §3.10.6). The contents of two strings s and t can be tested for equality by the method invocation s.equals(t). >
You almost **always** want to use `Objects.equals()`. In the **rare** situation where you **know** you're dealing with [interned](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#intern--) strings, you *can* use `==`.
From [JLS 3.10.5. *String Literals*](https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5):
> Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are \"interned\" so as to share unique instances, using the method String.intern. >
Similar examples can also be found in [JLS 3.10.5-1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#d5e1634).
### Other Methods To Consider
[String.equalsIgnoreCase()](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#equalsIgnoreCase-java.lang.String-) value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see [this question](https://stackoverflow.com/questions/44238749/equalsignorecase-not-working-as-intended).
[String.contentEquals()](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#contentEquals-java.lang.CharSequence-) compares the content of the `String` with the content of any `CharSequence` (available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you."}
{"_id": 124, "title": "", "text": "```java // These two have the same value new String(\"test\").equals(\"test\") // --> true
// ... but they are not the same object new String(\"test\") == \"test\" // --> false
// ... neither are these new String(\"test\") == new String(\"test\") // --> false
// ... but these are because literals are interned by // the compiler and thus refer to the same object \"test\" == \"test\" // --> true
// ... string literals are concatenated by the compiler // and the results are interned. \"test\" == \"te\" + \"st\" // --> true
// ... but you should really just call Objects.equals() Objects.equals(\"test\", new String(\"test\")) // --> true Objects.equals(null, \"test\") // --> false Objects.equals(null, null) // --> true
``` public static boolean equals(Object a, Object b) ```
Returns `true` if the arguments are equal to each other and `false` otherwise. Consequently, if both arguments are `null`, `true` is returned and if exactly one argument is `null`, `false` is returned. Otherwise, equality is determined by using the [`equals`](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)) method of the first argument.
**Parameters:**`a` - an object`b` - an object to be compared with `a` for equality**Returns:**`true` if the arguments are equal to each other and `false` otherwise**See Also:**[`Object.equals(Object)`](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object))"}
{"_id": 126, "title": "", "text": "Since Java 5 you can use [`Arrays.toString(arr)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#toString(int%5B%5D)) or [`Arrays.deepToString(arr)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#deepToString(java.lang.Object%5B%5D)) for arrays within arrays. Note that the `Object[]` version calls `.toString()` on each object in the array. The output is even decorated in the exact way you're asking.
Examples:
- Simple Array:
```java String[] array = new String[] {\"John\", \"Mary\", \"Bob\"}; System.out.println(Arrays.toString(array));
public static [String](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html) toString(int[] a)
Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets (`\"[]\"`). Adjacent elements are separated by the characters `\", \"` (a comma followed by a space). Elements are converted to strings as by `String.valueOf(int)`. Returns `\"null\"` if `a` is `null`.
**Parameters:**`a` - the array whose string representation to return**Returns:**a string representation of `a`**Since:**1.5"}
{"_id": 129, "title": "", "text": "Use the appropriately named method [`String#split()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#split(java.lang.String)).
Note that `split`'s argument is assumed to be a [regular expression](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#sum), so remember to escape [special characters](https://www.regular-expressions.info/characters.html) if necessary.
> there are 12 characters with special meanings: the backslash \\, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called \"metacharacters\". >
For instance, to split on a period/dot `.` (which means \"[any character](https://www.regular-expressions.info/dot.html)\" in regex), use either [backslash `\\`](https://www.regular-expressions.info/characters.html) to escape the individual special character like so `split(\"\\\\.\")`, or use [character class `[]`](https://www.regular-expressions.info/charclass.html) to represent literal character(s) like so `split(\"[.]\")`, or use [`Pattern#quote()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#quote(java.lang.String)) to escape the entire string like so `split(Pattern.quote(\".\"))`.
```java String[] parts = string.split(Pattern.quote(\".\")); // Split on the exact string.
```
To test beforehand if the string contains certain character(s), just use [`String#contains()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#contains(java.lang.CharSequence)).
```java if (string.contains(\"-\")) { // Split it. } else { throw new IllegalArgumentException(\"String \" + string + \" does not contain -\"); }
```
Note, this does not take a regular expression. For that, use [`String#matches()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#matches(java.lang.String)) instead.
If you'd like to retain the split character in the resulting parts, then make use of [positive lookaround](https://www.regular-expressions.info/lookaround.html). In case you want to have the split character to end up in left hand side, use positive lookbehind by prefixing `?<=` group on the pattern.
```"}
{"_id": 131, "title": "", "text": "- splitSplits this string around matches of the given [regular expression](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#sum).
public [String](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html)[] split([String](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html) regex)
This method works as if by invoking the two-argument [`split`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#split(java.lang.String,int)) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
The string `\"boo:and:foo\"`, for example, yields the following results with these expressions:
**Parameters:**`regex` - the delimiting regular expression**Returns:**the array of strings computed by splitting this string around matches of the given regular expression**Throws:**[`PatternSyntaxException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/PatternSyntaxException.html) - if the regular expression's syntax is invalid**Since:**1.4**See Also:** ◦ [`Pattern`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html)"}
{"_id": 132, "title": "", "text": "### The theory (for the language lawyers and the mathematically inclined):
`equals()` ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object))) must define an equivalence relation (it must be *reflexive*, *symmetric*, and *transitive*). In addition, it must be *consistent* (if the objects are not modified, then it must keep returning the same value). Furthermore, `o.equals(null)` must always return false.
`hashCode()` ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode())) must also be *consistent* (if the object is not modified in terms of `equals()`, it must keep returning the same value).
The **relation** between the two methods is:
> Whenever a.equals(b), then a.hashCode() must be same as b.hashCode(). >
### In practice:
If you override one, then you should override the other.
Use the same set of fields that you use to compute `equals()` to compute `hashCode()`.
Use the excellent helper classes [EqualsBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html) and [HashCodeBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html) from the [Apache Commons Lang](http://commons.apache.org/lang/) library. An example:
```java public class Person { private String name; private int age; // ...
@Override public int hashCode() { return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers // if deriving: appendSuper(super.hashCode()). append(name). append(age). toHashCode(); }
@Override public boolean equals(Object obj) { if (!(obj instanceof Person)) return false; if (obj == this) return true;
Person rhs = (Person) obj; return new EqualsBuilder(). // if deriving: appendSuper(super.equals(obj)). append(name, rhs.name). append(age, rhs.age). isEquals(); } }
```
### Also remember:
When using a hash-based [Collection](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html) or [Map](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html) such as [HashSet](http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html), [LinkedHashSet](http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html), [HashMap](http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html), [Hashtable](http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html), or [WeakHashMap](http://download.oracle.com/javase/1.4.2/docs/api/java/util/WeakHashMap.html), make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, [which has also other benefits](http://www.javapractices.com/topic/TopicAction.do?Id=29)."}
{"_id": 133, "title": "", "text": "```java public class Person { private String name; private int age; // ...
@Override public int hashCode() { return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers // if deriving: appendSuper(super.hashCode()). append(name). append(age). toHashCode(); }
@Override public boolean equals(Object obj) { if (!(obj instanceof Person)) return false; if (obj == this) return true;
Person rhs = (Person) obj; return new EqualsBuilder(). // if deriving: appendSuper(super.equals(obj)). append(name, rhs.name). append(age, rhs.age). isEquals(); } }
```"}
{"_id": 134, "title": "", "text": "- equalsIndicates whether some other object is \"equal to\" this one.
``` public boolean equals(Object obj) ```
The `equals` method implements an equivalence relation on non-null object references:
- It is *reflexive*: for any non-null reference value `x`, `x.equals(x)` should return `true`. - It is *symmetric*: for any non-null reference values `x` and `y`, `x.equals(y)` should return `true` if and only if `y.equals(x)` returns `true`. - It is *transitive*: for any non-null reference values `x`, `y`, and `z`, if `x.equals(y)` returns `true` and `y.equals(z)` returns `true`, then `x.equals(z)` should return `true`. - It is *consistent*: for any non-null reference values `x` and `y`, multiple invocations of `x.equals(y)` consistently return `true` or consistently return `false`, provided no information used in `equals` comparisons on the objects is modified. - For any non-null reference value `x`, `x.equals(null)` should return `false`.
The `equals` method for class `Object` implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values `x` and `y`, this method returns `true` if and only if `x` and `y` refer to the same object (`x == y` has the value `true`).
Note that it is generally necessary to override the `hashCode` method whenever this method is overridden, so as to maintain the general contract for the `hashCode` method, which states that equal objects must have equal hash codes.
**Parameters:**`obj` - the reference object with which to compare.**Returns:**`true` if this object is the same as the obj argument; `false` otherwise.**See Also:**[`hashCode()`](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()), [`HashMap`](https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html)"}
{"_id": 135, "title": "", "text": "That's the hard way, and those `java.util.Date` setter methods have been deprecated since Java 1.1 (1997). Moreover, the whole `java.util.Date` class was de-facto deprecated (discommended) since introduction of `java.time` API in Java 8 (2014).
Simply format the date using [`DateTimeFormatter`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html) with a pattern matching the input string ([the tutorial is available here](https://docs.oracle.com/javase/tutorial/datetime/iso/format.html)).
In your specific case of \"January 2, 2010\" as the input string:
1. \"January\" is the full text month, so use the `MMMM` pattern for it 2. \"2\" is the short day-of-month, so use the `d` pattern for it. 3. \"2010\" is the 4-digit year, so use the `yyyy` pattern for it.
Note: if your format pattern happens to contain the time part as well, then use [`LocalDateTime#parse(text, formatter)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDateTime.html#parse(java.lang.CharSequence,java.time.format.DateTimeFormatter)) instead of [`LocalDate#parse(text, formatter)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDate.html#parse(java.lang.CharSequence,java.time.format.DateTimeFormatter)). And, if your format pattern happens to contain the time zone as well, then use [`ZonedDateTime#parse(text, formatter)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/ZonedDateDate.html#parse(java.lang.CharSequence,java.time.format.DateTimeFormatter)) instead.
Here's an extract of relevance from [the javadoc](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html), listing all available format patterns:
| Symbol | Meaning | Presentation | Examples | | --- | --- | --- | --- | | G | era | text | AD; Anno Domini; A | | u | year | year | 2004; 04 | | y | year-of-era | year | 2004; 04 | | D | day-of-year | number | 189 | | M/L | month-of-year | number/text | 7; 07; Jul; July; J | | d | day-of-month | number | 10 | | Q/q | quarter-of-year | number/text | 3; 03; Q3; 3rd quarter | | Y | week-based-year | year | 1996; 96 | | w | week-of-week-based-year | number | 27 | | W | week-of-month | number | 4 | | E | day-of-week | text | Tue; Tuesday; T | | e/c | localized day-of-week | number/text | 2; 02; Tue; Tuesday; T | | F | week-of-month | number | 3 | | a | am-pm-of-day | text | PM | | h | clock-hour-of-am-pm (1-12) | number | 12 | | K | hour-of-am-pm (0-11) | number | 0 | | k | clock-hour-of-am-pm (1-24) | number | 0 | | H | hour-of-day (0-23) | number | 0 | | m | minute-of-hour | number | 30 | | s | second-of-minute | number | 55 | | S | fraction-of-second | fraction | 978 | | A | milli-of-day | number | 1234 | | n | nano-of-second | number | 987654321 | | N | nano-of-day | number | 1234000000 | | V | time-zone ID | zone-id | America/Los_Angeles; Z; -08:30 | | z | time-zone name | zone-name | Pacific Standard Time; PST | | O | localized zone-offset | offset-O | GMT+8; GMT+08:00; UTC-08:00; | | X | zone-offset 'Z' for zero | offset-X | Z; -08; -0830; -08:30; -083015; -08:30:15; | | x | zone-offset | offset-x | +0000; -08; -0830; -08:30; -083015; -08:30:15; | | Z | zone-offset | offset-Z | +0000; -0800; -08:00; |
Do note that it has several [predefined formatters](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html#predefined) for the more popular patterns. So instead of e.g. `DateTimeFormatter.ofPattern(\"EEE, d MMM yyyy HH:mm:ss Z\", Locale.ENGLISH);`, you could use `DateTimeFormatter.RFC_1123_DATE_TIME`. This is possible because they are, on the contrary to `SimpleDateFormat`, thread safe. You could thus also define your own, if necessary.
For a particular input string format, you don't need to use an explicit `DateTimeFormatter`: a standard [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date, like 2016-09-26T17:44:57Z, can be parsed directly with [`LocalDateTime#parse(text)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDateTime.html#parse(java.lang.CharSequence)) as it already uses the [`ISO_LOCAL_DATE_TIME`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE_TIME) formatter. Similarly, [`LocalDate#parse(text)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDate.html#parse(java.lang.CharSequence)) parses an ISO date without the time component (see [`ISO_LOCAL_DATE`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE)), and [`ZonedDateTime#parse(text)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/ZonedDateTime.html#parse(java.lang.CharSequence)) parses an ISO date with an offset and time zone added (see [`ISO_ZONED_DATE_TIME`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html#ISO_ZONED_DATE_TIME)).
---
## Pre-Java 8
In case you're not on Java 8 yet, or are forced to use `java.util.Date`, then format the date using [`SimpleDateFormat`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/SimpleDateFormat.html) using a format pattern matching the input string.
```java String string = \"January 2, 2010\"; DateFormat format = new SimpleDateFormat(\"MMMM d, yyyy\", Locale.ENGLISH); Date date = format.parse(string); System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010
```
Note the importance of the explicit `Locale` argument. If you omit it, then it will use the [default locale](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Locale.html#getDefault()) which is not necessarily English as used in the month name of the input string. If the locale doesn't match with the input string, then you would confusingly get a `java.text.ParseException` even though when the format pattern seems valid.
Here's an extract of relevance from [the javadoc](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/SimpleDateFormat.html), listing all available format patterns:
| Letter | Date or Time Component | Presentation | Examples | | --- | --- | --- | --- | | G | Era designator | Text | AD | | y | Year | Year | 1996; 96 | | Y | Week year | Year | 2009; 09 | | M/L | Month in year | Month | July; Jul; 07 | | w | Week in year | Number | 27 | | W | Week in month | Number | 2 | | D | Day in year | Number | 189 | | d | Day in month | Number | 10 | | F | Day of week in month | Number | 2 | | E | Day in week | Text | Tuesday; Tue | | u | Day number of week | Number | 1 | | a | Am/pm marker | Text | PM | | H | Hour in day (0-23) | Number | 0 | | k | Hour in day (1-24) | Number | 24 | | K | Hour in am/pm (0-11) | Number | 0 | | h | Hour in am/pm (1-12) | Number | 12 | | m | Minute in hour | Number | 30 | | s | Second in minute | Number | 55 | | S | Millisecond | Number | 978 | | z | Time zone | General time zone | Pacific Standard Time; PST; GMT-08:00 | | Z | Time zone | RFC 822 time zone | -0800 | | X | Time zone | ISO 8601 time zone | -08; -0800; -08:00 |
Note that the patterns are case sensitive and that text based patterns of four characters or more represent the full form; otherwise a short or abbreviated form is used if available. So e.g. `MMMMM` or more is unnecessary.
Here are some examples of valid `SimpleDateFormat` patterns to parse a given string to date:
| Input string | Pattern | | --- | --- | | 2001.07.04 AD at 12:08:56 PDT | yyyy.MM.dd G 'at' HH:mm:ss z | | Wed, Jul 4, '01 | EEE, MMM d, ''yy | | 12:08 PM | h:mm a | | 12 o'clock PM, Pacific Daylight Time | hh 'o''clock' a, zzzz | | 0:08 PM, PDT | K:mm a, z | | 02001.July.04 AD 12:08 PM | yyyyy.MMMM.dd GGG hh:mm aaa | | Wed, 4 Jul 2001 12:08:56 -0700 | EEE, d MMM yyyy HH:mm:ss Z | | 010704120856-0700 | yyMMddHHmmssZ | | 2001-07-04T12:08:56.235-0700 | yyyy-MM-dd'T'HH:mm:ss.SSSZ | | 2001-07-04T12:08:56.235-07:00 | yyyy-MM-dd'T'HH:mm:ss.SSSXXX | | 2001-W27-3 | YYYY-'W'ww-u |
An important note is that `SimpleDateFormat` is **not** thread safe. In other words, you should never declare and assign it as a static or instance variable and then reuse it from different methods/threads. You should always create it brand new within the method local scope."}
{"_id": 136, "title": "", "text": "```java String string = \"January 2, 2010\"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"MMMM d, yyyy\", Locale.ENGLISH); LocalDate date = LocalDate.parse(string, formatter); System.out.println(date); // 2010-01-02
```"}
{"_id": 137, "title": "", "text": "# Class DateTimeFormatter
public final class **DateTimeFormatter**extends [Object](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html)
Formatter for printing and parsing date-time objects.
This class provides the main application entry point for printing and parsing and provides common implementations of `DateTimeFormatter`:
- Using predefined constants, such as [`ISO_LOCAL_DATE`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html#ISO_LOCAL_DATE) - Using pattern letters, such as `uuuu-MMM-dd` - Using localized styles, such as `long` or `medium`
More complex formatters are provided by [`DateTimeFormatterBuilder`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatterBuilder.html).
The main date-time classes provide two methods - one for formatting, `format(DateTimeFormatter formatter)`, and one for parsing, `parse(CharSequence text, DateTimeFormatter formatter)`.
For example:
> LocalDate date = LocalDate.now(); String text = date.format(formatter); LocalDate parsedDate = LocalDate.parse(text, formatter); >"}
{"_id": 138, "title": "", "text": "Use [`setRoundingMode`](http://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html#setRoundingMode(java.math.RoundingMode)), set the [`RoundingMode`](http://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html) explicitly to handle your issue with the half-even round, then use the format pattern for your required output.
Example:
```java DecimalFormat df = new DecimalFormat(\"#.####\"); df.setRoundingMode(RoundingMode.CEILING); for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) { Double d = n.doubleValue(); System.out.println(df.format(d)); }
```
gives the output:
```java 12 123.1235 0.23 0.1 2341234.2125
```
---
**EDIT**: The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:
```java Double d = n.doubleValue() + 1e-6;
```
To round down, subtract the accuracy."}
{"_id": 139, "title": "", "text": "```java DecimalFormat df = new DecimalFormat(\"#.####\"); df.setRoundingMode(RoundingMode.CEILING); for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) { Double d = n.doubleValue(); System.out.println(df.format(d)); }
```"}
{"_id": 140, "title": "", "text": "## Class DecimalFormat
- [java.lang.Object](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html) - [java.text.Format](https://docs.oracle.com/javase/8/docs/api/java/text/Format.html)[java.text.NumberFormat](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html)java.text.DecimalFormat - **All Implemented Interfaces:**[Serializable](https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html), [Cloneable](https://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html)`DecimalFormat` is a concrete subclass of `NumberFormat` that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.
---
``` public classDecimalFormat extendsNumberFormat ```
To obtain a `NumberFormat` for a specific locale, including the default locale, call one of `NumberFormat`'s factory methods, such as `getInstance()`. In general, do not call the `DecimalFormat` constructors directly, since the `NumberFormat` factory methods may return subclasses other than `DecimalFormat`. If you need to customize the format object, do something like this:
> NumberFormat f = NumberFormat.getInstance(loc); if (f instanceof DecimalFormat) { ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true); } >
A `DecimalFormat` comprises a *pattern* and a set of *symbols*. The pattern may be set directly using `applyPattern()`, or indirectly using the API methods. The symbols are stored in a `DecimalFormatSymbols` object. When using the `NumberFormat` factory methods, the pattern and symbols are read from localized `ResourceBundle`s."}
{"_id": 141, "title": "", "text": "*First a disclaimer beforehand: the posted code snippets are all basic examples. You'll need to handle trivial `IOException`s and `RuntimeException`s like `NullPointerException`, `ArrayIndexOutOfBoundsException` and consorts yourself.*
*In case you're developing for Android instead of Java, note also that since introduction of API level 28, cleartext HTTP requests are [disabled by default](https://developer.android.com/about/versions/pie/android-9.0-changes-28#tls-enabled). You are encouraged to use `HttpsURLConnection`. When really necessary, cleartext can be enabled in the Application Manifest.*
---
### Preparing
We first need to know at least the URL and the charset. The parameters are optional and depend on the functional requirements.
```java String url = \"http://example.com\"; String charset = \"UTF-8\"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name() String param1 = \"value1\"; String param2 = \"value2\"; // ...
The query parameters must be in `name=value` format and be concatenated by `&`. You would normally also [URL-encode](http://en.wikipedia.org/wiki/Percent-encoding) the query parameters with the specified charset using [`URLEncoder#encode()`](http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html#encode-java.lang.String-java.lang.String-).
The `String#format()` is just for convenience. I prefer it when I would need the String concatenation operator `+` more than twice.
---
### Firing an [HTTP GET](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) request with (optionally) query parameters
It's a trivial task. It's the default request method.
Any query string should be concatenated to the URL using `?`. The [`Accept-Charset`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2) header may hint the server what encoding the parameters are in. If you don't send any query string, then you can leave the `Accept-Charset` header away. If you don't need to set any headers, then you can even use the [`URL#openStream()`](http://docs.oracle.com/javase/8/docs/api/java/net/URL.html#openStream%28%29) shortcut method.
```java InputStream response = new URL(url).openStream(); // ...
```
Either way, if the other side is an [`HttpServlet`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html), then its [`doGet()`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html#doGet%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29) method will be called and the parameters will be available by [`HttpServletRequest#getParameter()`](http://docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29).
For testing purposes, you can print the response body to [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29) as below:
### Firing an [HTTP POST](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5) request with query parameters
Setting the [`URLConnection#setDoOutput()`](http://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#setDoOutput%28boolean%29) to `true` implicitly sets the request method to POST. The standard HTTP POST as web forms do is of type `application/x-www-form-urlencoded` wherein the query string is written to the request body.
```java URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty(\"Accept-Charset\", charset); connection.setRequestProperty(\"Content-Type\", \"application/x-www-form-urlencoded;charset=\" + charset);
Note: whenever you'd like to submit a HTML form programmatically, don't forget to take the `name=value` pairs of any `` elements into the query string and of course also the `name=value` pair of the `` element which you'd like to \"press\" programmatically (because that's usually been used in the server side to distinguish if a button was pressed and if so, which one).
You can also cast the obtained [`URLConnection`](http://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html) to [`HttpURLConnection`](http://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html) and use its [`HttpURLConnection#setRequestMethod()`](http://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#setRequestMethod%28java.lang.String%29) instead. But if you're trying to use the connection for output you still need to set [`URLConnection#setDoOutput()`](http://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#setDoOutput%28boolean%29) to `true`.
```java HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.setRequestMethod(\"POST\"); // ...
```
Either way, if the other side is an [`HttpServlet`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html), then its [`doPost()`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html#doPost%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29) method will be called and the parameters will be available by [`HttpServletRequest#getParameter()`](http://docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29).
---
### Actually firing the HTTP request
You can fire the HTTP request explicitly with [`URLConnection#connect()`](http://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#connect%28%29), but the request will automatically be fired on demand when you want to get any information about the HTTP response, such as the response body using [`URLConnection#getInputStream()`](http://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#getInputStream%28%29) and so on. The above examples does exactly that, so the `connect()` call is in fact superfluous.
---
### Timeouts
You can use [`URLConnection#setConnectTimeout()`](https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#setConnectTimeout-int-) to set the connect timeout and [`URLConnection#setReadTimeout()`](https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#setReadTimeout-int-) to set the read timeout.
The default is basically \"no timeout\". So you'd like to set these yourself. For example:
There's however a caveat with the read timeout when using Sun/Oracle based JRE. It will silently retry the reading before throwing the timeout exception, most probably merely to have any successfull reading ready in the cache. See also [Android (Java) HttpURLConnection silent retry on 'read' timeout](https://stackoverflow.com/questions/27094544/android-java-httpurlconnection-silent-retry-on-read-timeout/37675253#37675253) This is okayish for GET, but absolutely wrong for POST. In case you're using a Sun/Oracle based JRE, you'll want to turn off that as follows:
This will only slightly impact the performance. In case that's undesireable, then consider switching to a different HTTP client such as [OkHttp](https://square.github.io/okhttp/).
When the `Content-Type` contains a `charset` parameter, then the response body is likely text based and we'd like to process the response body with the server-side specified character encoding then.
for (String param : contentType.replace(\" \", \"\").split(\";\")) { if (param.startsWith(\"charset=\")) { charset = param.split(\"=\", 2)[1]; break; } }
if (charset != null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) { for (String line; (line = reader.readLine()) != null;) { // ... System.out.println(line)? } } } else { // It's likely binary content, use InputStream/OutputStream. }
```
---
### Maintaining the session
The server side session is usually backed by a cookie. Some web forms require that you're logged in and/or are tracked by a session. You can use the [`CookieHandler`](http://docs.oracle.com/javase/8/docs/api/java/net/CookieHandler.html) API to maintain cookies. You need to prepare a [`CookieManager`](http://docs.oracle.com/javase/8/docs/api/java/net/CookieManager.html) with a [`CookiePolicy`](http://docs.oracle.com/javase/8/docs/api/java/net/CookiePolicy.html) of [`ACCEPT_ALL`](http://docs.oracle.com/javase/8/docs/api/java/net/CookiePolicy.html#ACCEPT_ALL) before sending all HTTP requests.
```java // First set the default cookie manager. CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager. URLConnection connection = new URL(url).openConnection(); // ...
connection = new URL(url).openConnection(); // ...
connection = new URL(url).openConnection(); // ...
```
Note that this is known to not always work properly in all circumstances. If it fails for you, then best is to manually gather and set the cookie headers. You basically need to grab all `Set-Cookie` headers from the response of the login or the first `GET` request and then pass this through the subsequent requests.
```java // Gather all cookies on the first request. URLConnection connection = new URL(url).openConnection(); List cookies = connection.getHeaderFields().get(\"Set-Cookie\"); // ...
// Then use the same cookies on all subsequent requests. connection = new URL(url).openConnection(); for (String cookie : cookies) { connection.addRequestProperty(\"Cookie\", cookie.split(\";\", 2)[0]); } // ...
```
The `split(\";\", 2)[0]` is there to get rid of cookie attributes which are irrelevant for the server side like `expires`, `path`, etc. Alternatively, you could also use `cookie.substring(0, cookie.indexOf(';'))` instead of `split()`.
---
### Streaming mode
The [`HttpURLConnection`](http://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html) will by default buffer the *entire* request body before actually sending it, regardless of whether you've set a fixed content length yourself using `connection.setRequestProperty(\"Content-Length\", contentLength);`. This may cause `OutOfMemoryException`s whenever you concurrently send large POST requests (e.g. uploading files). To avoid this, you would like to set the [`HttpURLConnection#setFixedLengthStreamingMode()`](http://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#setFixedLengthStreamingMode%28int%29).
But if the content length is really not known beforehand, then you can make use of chunked streaming mode by setting the [`HttpURLConnection#setChunkedStreamingMode()`](http://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#setChunkedStreamingMode%28int%29) accordingly. This will set the HTTP [`Transfer-Encoding`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.41) header to `chunked` which will force the request body being sent in chunks. The below example will send the body in chunks of 1 KB.
It can happen that [a request returns an unexpected response, while it works fine with a real web browser](https://stackoverflow.com/questions/13670692/403-forbidden-with-java-but-not-web-browser). The server side is probably blocking requests based on the [`User-Agent`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43) request header. The `URLConnection` will by default set it to `Java/1.6.0_19` where the last part is obviously the JRE version. You can override this as follows:
```java connection.setRequestProperty(\"User-Agent\", \"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36\"); // Do as if you're using Chrome 41 on Windows 7.
```
Use the User-Agent string from a [recent browser](http://www.useragentstring.com/pages/useragentstring.php).
---
### Error handling
If the HTTP response code is `4nn` (Client Error) or `5nn` (Server Error), then you may want to read the `HttpURLConnection#getErrorStream()` to see if the server has sent any useful error information.
If the HTTP response code is -1, then something went wrong with connection and response handling. The `HttpURLConnection` implementation is in older JREs somewhat buggy with keeping connections alive. You may want to turn it off by setting the `http.keepAlive` system property to `false`. You can do this programmatically in the beginning of your application by:
You'd normally use [`multipart/form-data`](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2) encoding for mixed POST content (binary and character data). The encoding is in more detail described in [RFC2388](http://www.faqs.org/rfcs/rfc2388.html).
```java String param = \"value\"; File textFile = new File(\"/path/to/file.txt\"); File binaryFile = new File(\"/path/to/file.bin\"); String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value. String CRLF = \"\\r\\n\"; // Line separator required by multipart/form-data. URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty(\"Content-Type\", \"multipart/form-data; boundary=\" + boundary);
// Send text file. writer.append(\"--\" + boundary).append(CRLF); writer.append(\"Content-Disposition: form-data; name=\\\"textFile\\\"; filename=\\\"\" + textFile.getName() + \"\\\"\").append(CRLF); writer.append(\"Content-Type: text/plain; charset=\" + charset).append(CRLF); // Text file itself must be saved in this charset! writer.append(CRLF).flush(); Files.copy(textFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// Send binary file. writer.append(\"--\" + boundary).append(CRLF); writer.append(\"Content-Disposition: form-data; name=\\\"binaryFile\\\"; filename=\\\"\" + binaryFile.getName() + \"\\\"\").append(CRLF); writer.append(\"Content-Type: \" + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF); writer.append(\"Content-Transfer-Encoding: binary\").append(CRLF); writer.append(CRLF).flush(); Files.copy(binaryFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data. writer.append(\"--\" + boundary + \"--\").append(CRLF).flush(); }
```
If the other side is an [`HttpServlet`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html), then its [`doPost()`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServlet.html#doPost%28javax.servlet.http.HttpServletRequest,%20javax.servlet.http.HttpServletResponse%29) method will be called and the parts will be available by [`HttpServletRequest#getPart()`](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#getPart%28java.lang.String%29) (note, thus **not** `getParameter()` and so on!). The `getPart()` method is however relatively new, it's introduced in Servlet 3.0 (Glassfish 3, Tomcat 7, etc.). Prior to Servlet 3.0, your best choice is using [Apache Commons FileUpload](http://commons.apache.org/fileupload) to parse a `multipart/form-data` request. Also see [this answer](https://stackoverflow.com/questions/2422468/upload-big-file-to-servlet/2424824#2424824) for examples of both the FileUpload and the Servelt 3.0 approaches.
---
### Dealing with untrusted or misconfigured HTTPS sites
*In case you're developing for Android instead of Java, **be careful**: the workaround below may save your day if you don't have correct certificates deployed during development. But you should not use it for production. These days (April 2021) Google will not allow your app be distributed on Play Store if they detect insecure hostname verifier, see https://support.google.com/faqs/answer/7188426.*
Sometimes you need to connect an HTTPS URL, perhaps because you're writing a web scraper. In that case, you may likely face a `javax.net.ssl.SSLException: Not trusted server certificate` on some HTTPS sites who doesn't keep their SSL certificates up to date, or a `java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found` or `javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name` on some misconfigured HTTPS sites.
The following one-time-run `static` initializer in your web scraper class should make `HttpsURLConnection` more lenient as to those HTTPS sites and thus not throw those exceptions anymore.
```java static { TrustManager[] trustAllCertificates = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; // Not relevant. } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. } } };
HostnameVerifier trustAllHostnames = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; // Just allow them all. } };
If all you want is parsing and extracting data from HTML, then better use a HTML parser like [Jsoup](http://jsoup.org/).
- [What are the pros/cons of leading HTML parsers in Java](https://stackoverflow.com/questions/3152138/what-are-the-pros-and-cons-of-the-leading-java-html-parsers/3154281#3154281) - [How to scan and extract a webpage in Java](https://stackoverflow.com/questions/2835505/how-to-scan-a-website-or-page-for-info-and-bring-it-into-my-program/2835555#2835555)"}
{"_id": 142, "title": "", "text": "```java URLConnection connection = new URL(url + \"?\" + query).openConnection(); connection.setRequestProperty(\"Accept-Charset\", charset); InputStream response = connection.getInputStream(); // ...
```"}
{"_id": 143, "title": "", "text": "- encodeTranslates a string into `application/x-www-form-urlencoded` format using a specific encoding scheme. This method uses the supplied encoding scheme to obtain the bytes for unsafe characters.
``` public staticString encode(String s, String enc) throwsUnsupportedEncodingException ```
***Note:** The [World Wide Web Consortium Recommendation](http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars) states that UTF-8 should be used. Not doing so may introduce incompatibilities.*
**Parameters:**`s` - `String` to be translated.`enc` - The name of a supported [character encoding](https://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html#charenc).**Returns:**the translated `String`.**Throws:**[`UnsupportedEncodingException`](https://docs.oracle.com/javase/8/docs/api/java/io/UnsupportedEncodingException.html) - If the named encoding is not supported**Since:**1.4**See Also:**[`URLDecoder.decode(java.lang.String, java.lang.String)`](https://docs.oracle.com/javase/8/docs/api/java/net/URLDecoder.html#decode-java.lang.String-java.lang.String-)"}
{"_id": 144, "title": "", "text": "I have to ask a question in return: is your `GenSet` \"checked\" or \"unchecked\"? What does that mean?
- **Checked**: *strong typing*. `GenSet` knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a `Class` argument, and methods will throw an exception when they are passed arguments that are not of type `E`. See [`Collections.checkedCollection`](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#checkedCollection%28java.util.Collection,%20java.lang.Class%29). - > in that case, you should write:
```java public class GenSet {
private E[] a;
public GenSet(Class c, int s) { // Use Array native method to create array // of a type only known at run time @SuppressWarnings(\"unchecked\") final E[] a = (E[]) Array.newInstance(c, s); this.a = a; }
E get(int i) { return a[i]; } }
```
- **Unchecked**: *weak typing*. No type checking is actually done on any of the objects passed as argument. - > in that case, you should write
```java public class GenSet {
private Object[] a;
public GenSet(int s) { a = new Object[s]; }
E get(int i) { @SuppressWarnings(\"unchecked\") final E e = (E) a[i]; return e; } }
```
Note that the component type of the array should be the [*erasure*](http://docs.oracle.com/javase/tutorial/java/generics/erasure.html) of the type parameter:
```java public class GenSet { // E has an upper bound of Foo
private Foo[] a; // E erases to Foo, so use Foo[]
public GenSet(int s) { a = new Foo[s]; }
... }
```
All of this results from a known, and deliberate, weakness of generics in Java: it was implemented using erasure, so \"generic\" classes don't know what type argument they were created with at run time, and therefore can not provide type-safety unless some explicit mechanism (type-checking) is implemented."}
{"_id": 145, "title": "", "text": " ```java public class GenSet {
private Object[] a;
public GenSet(int s) { a = new Object[s]; }
E get(int i) { @SuppressWarnings(\"unchecked\") final E e = (E) a[i]; return e; } }
```"}
{"_id": 146, "title": "", "text": "- checkedCollectionReturns a dynamically typesafe view of the specified collection. Any attempt to insert an element of the wrong type will result in an immediate [`ClassCastException`](https://docs.oracle.com/javase/7/docs/api/java/lang/ClassCastException.html). Assuming a collection contains no incorrectly typed elements prior to the time a dynamically typesafe view is generated, and that all subsequent access to the collection takes place through the view, it is *guaranteed* that the collection cannot contain an incorrectly typed element.may be replaced temporarily by this one:Running the program again will cause it to fail at the point where an incorrectly typed element is inserted into the collection, clearly identifying the source of the problem. Once the problem is fixed, the modified declaration may be reverted back to the original.
``` public static Collection checkedCollection(Collection c, Class type) ```
The generics mechanism in the language provides compile-time (static) type checking, but it is possible to defeat this mechanism with unchecked casts. Usually this is not a problem, as the compiler issues warnings on all such unchecked operations. There are, however, times when static type checking alone is not sufficient. For example, suppose a collection is passed to a third-party library and it is imperative that the library code not corrupt the collection by inserting an element of the wrong type.
Another use of dynamically typesafe views is debugging. Suppose a program fails with a `ClassCastException`, indicating that an incorrectly typed element was put into a parameterized collection. Unfortunately, the exception can occur at any time after the erroneous element is inserted, so it typically provides little or no information as to the real source of the problem. If the problem is reproducible, one can quickly determine its source by temporarily modifying the program to wrap the collection with a dynamically typesafe view. For example, this declaration:
``` Collection c = new HashSet();
```
``` Collection c = Collections.checkedCollection( new HashSet(), String.class);
```
The returned collection does *not* pass the hashCode and equals operations through to the backing collection, but relies on `Object`'s `equals` and `hashCode` methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.
The returned collection will be serializable if the specified collection is serializable.
Since `null` is considered to be a value of any reference type, the returned collection permits insertion of null elements whenever the backing collection does.
**Parameters:**`c` - the collection for which a dynamically typesafe view is to be returned`type` - the type of element that `c` is permitted to hold**Returns:**a dynamically typesafe view of the specified collection**Since:**1.5"}
{"_id": 147, "title": "", "text": "```java for (Iterator i = someIterable.iterator(); i.hasNext();) { String item = i.next(); System.out.println(item); }
```
Note that if you need to use `i.remove();` in your loop, or access the actual iterator in some way, you cannot use the `for ( : )` idiom, since the actual iterator is merely inferred.
As was noted by Denis Bueno, this code works for any object that implements the [`Iterable` interface](http://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html).
If the right-hand side of the `for (:)` idiom is an array rather than an `Iterable` object, the internal code uses an int index counter and checks against `array.length` instead. See the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.14.2).
```java for (int i = 0; i < someArray.length; i++) { String item = someArray[i]; System.out.println(item); } ```"}
{"_id": 148, "title": "", "text": "```java for (Iterator i = someIterable.iterator(); i.hasNext();) { String item = i.next(); System.out.println(item); }
Implementing this interface allows an object to be the target of the \"for-each loop\" statement. See [**For-each Loop**](https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html)
**Since:**1.5**See The Java™ Language Specification:**14.14.2 The enhanced for statement
- *Method Summary***All MethodsInstance MethodsAbstract MethodsDefault Methods**Modifier and TypeMethod and Description`default void[**forEach**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#forEach-java.util.function.Consumer-)([**Consumer**](https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html) super [**T**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html)> action)`Performs the given action for each element of the `Iterable` until all elements have been processed or the action throws an exception.[**`Iterator**](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)<[**T**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html)>[**iterator**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#iterator--)()`Returns an iterator over elements of type `T`.`default [**Spliterator**](https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html)<[**T**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html)>[**spliterator**](https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html#spliterator--)()`Creates a [**`Spliterator`**](https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html) over the elements described by this `Iterable`."}
{"_id": 150, "title": "", "text": "Are you doing this for logging purposes? If so there are [several libraries for this](http://en.wikipedia.org/wiki/Java_logging_framework). Two of the most popular are [Log4j](http://logging.apache.org/log4j/) and [Logback](http://logback.qos.ch/).
## Java 7+
For a one-time task, the [Files class](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) makes this easy:
```java try { Files.write(Paths.get(\"myfile.txt\"), \"the text\".getBytes(), StandardOpenOption.APPEND); }catch (IOException e) { //exception handling left as an exercise for the reader }
```
**Careful**: The above approach will throw a `NoSuchFileException` if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both `CREATE` and `APPEND` options, which will create the file first if it doesn't already exist:
However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a `BufferedWriter` is faster:
```java try(FileWriter fw = new FileWriter(\"myfile.txt\", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println(\"the text\"); //more code out.println(\"more text\"); //more code } catch (IOException e) { //exception handling left as an exercise for the reader }
```
**Notes:**
- The second parameter to the `FileWriter` constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.) - Using a `BufferedWriter` is recommended for an expensive writer (such as `FileWriter`). - Using a `PrintWriter` gives you access to `println` syntax that you're probably used to from `System.out`. - But the `BufferedWriter` and `PrintWriter` wrappers are not strictly necessary.
---
## Older Java
```java try { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(\"myfile.txt\", true))); out.println(\"the text\"); out.close(); } catch (IOException e) { //exception handling left as an exercise for the reader }
```
---
## Exception Handling
If you need robust exception handling for older Java, it gets very verbose:
```java FileWriter fw = null; BufferedWriter bw = null; PrintWriter out = null; try { fw = new FileWriter(\"myfile.txt\", true); bw = new BufferedWriter(fw); out = new PrintWriter(bw); out.println(\"the text\"); out.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } finally { try { if(out != null) out.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } try { if(bw != null) bw.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } try { if(fw != null) fw.close(); } catch (IOException e) { //exception handling left as an exercise for the reader } } ```"}
{"_id": 151, "title": "", "text": "```java try { Files.write(Paths.get(\"myfile.txt\"), \"the text\".getBytes(), StandardOpenOption.APPEND); }catch (IOException e) { //exception handling left as an exercise for the reader }
- newInputStreamOpens a file, returning an input stream to read from the file. The stream will not be buffered, and is not required to support the [`mark`](https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#mark(int)) or [`reset`](https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#reset()) methods. The stream will be safe for access by multiple concurrent threads. Reading commences at the beginning of the file. Whether the returned stream is *asynchronously closeable* and/or *interruptible* is highly file system provider specific and therefore not specified.
``` public staticInputStream newInputStream(Path path, OpenOption... options) throwsIOException ```
The `options` parameter determines how the file is opened. If no options are present then it is equivalent to opening the file with the [`READ`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#READ) option. In addition to the `READ` option, an implementation may also support additional implementation specific options.
**Parameters:**`path` - the path to the file to open`options` - options specifying how the file is opened**Returns:**a new input stream**Throws:**[`IllegalArgumentException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html) - if an invalid combination of options is specified[`UnsupportedOperationException`](https://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html) - if an unsupported option is specified[`IOException`](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) - if an I/O error occurs[`SecurityException`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityException.html) - In the case of the default provider, and a security manager is installed, the [`checkRead`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkRead(java.lang.String)) method is invoked to check read access to the file.
- newOutputStreamOpens or creates a file, returning an output stream that may be used to write bytes to the file. The resulting stream will not be buffered. The stream will be safe for access by multiple concurrent threads. Whether the returned stream is *asynchronously closeable* and/or *interruptible* is highly file system provider specific and therefore not specified.
``` public staticOutputStream newOutputStream(Path path, OpenOption... options) throwsIOException ```
This method opens or creates a file in exactly the manner specified by the [`newByteChannel`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newByteChannel(java.nio.file.Path,%20java.util.Set,%20java.nio.file.attribute.FileAttribute...)) method with the exception that the [`READ`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#READ) option may not be present in the array of options. If no options are present then this method works as if the [`CREATE`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#CREATE), [`TRUNCATE_EXISTING`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#TRUNCATE_EXISTING), and [`WRITE`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#WRITE) options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing [`regular-file`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#isRegularFile(java.nio.file.Path,%20java.nio.file.LinkOption...)) to a size of `0` if it exists.
**Usage Examples:**
``` Path path = ...
// truncate and overwrite an existing file, or create the file if // it doesn't initially exist OutputStream out = Files.newOutputStream(path);
// append to an existing file, fail if the file does not exist out = Files.newOutputStream(path, APPEND);
// append to an existing file, create file if it doesn't initially exist out = Files.newOutputStream(path, CREATE, APPEND);
// always create new file, failing if it already exists out = Files.newOutputStream(path, CREATE_NEW);
```
**Parameters:**`path` - the path to the file to open or create`options` - options specifying how the file is opened**Returns:**a new output stream**Throws:**[`IllegalArgumentException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html) - if `options` contains an invalid combination of options[`UnsupportedOperationException`](https://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html) - if an unsupported option is specified[`IOException`](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) - if an I/O error occurs[`SecurityException`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityException.html) - In the case of the default provider, and a security manager is installed, the [`checkWrite`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkWrite(java.lang.String)) method is invoked to check write access to the file. The [`checkDelete`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkDelete(java.lang.String)) method is invoked to check delete access if the file is opened with the `DELETE_ON_CLOSE` option."}
{"_id": 153, "title": "", "text": "From the [Java Tutorial](http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html):
> Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. >
Static nested classes are accessed using the enclosing class name:
```java OuterClass.StaticNestedClass
```
For example, to create an object for the static nested class, use this syntax:
```java OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
```
Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:
```java class OuterClass { ... class InnerClass { ... } }
```
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
For completeness note that there is also such a thing as an [inner class *without* an enclosing instance](https://stackoverflow.com/questions/20468856/is-it-true-that-every-inner-class-requires-an-enclosing-instance):
```java class A { int t() { return 1; } static A a = new A() { int t() { return 2; } }; }
```
Here, `new A() { ... }` is an *inner class defined in a static context* and does not have an enclosing instance."}
{"_id": 154, "title": "", "text": " ```java class OuterClass { ... class InnerClass { ... } }
The Java programming language allows you to define a class within another class. Such a class is called a *nested class* and is illustrated here:
`class OuterClass { ... class NestedClass { ... } }`
---
**Terminology:**
Nested classes are divided into two categories: non-static and static. Non-static nested classes are called
*inner classes*
. Nested classes that are declared
``` static ```
are called
*static nested classes*
.
---
`class OuterClass { ... class InnerClass { ... } static class StaticNestedClass { ... } }`
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class. As a member of the `OuterClass`, a nested class can be declared `private`, `public`, `protected`, or *package private*. (Recall that outer classes can only be declared `public` or *package private*.)"}
{"_id": 156, "title": "", "text": "There are two types of array.
## One Dimensional Array
Syntax for default values:
```java int[] num = new int[5];
```
Or (less preferred)
```java int num[] = new int[5];
```
Syntax with values given (variable/field initialization):
```java int[] num = {1,2,3,4,5};
```
Or (less preferred)
```java int num[] = {1, 2, 3, 4, 5};
```
Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all.
```java for (int i=0; i<(num.length); i++ ) { for (int j=0;j System.out.println(num[i][j]); }
```
Alternatively:
```java for (int[] a : num) { for (int i : a) { System.out.println(i); } }
```
Ragged arrays are multidimensional arrays.
For explanation see multidimensional array detail at [the official java tutorials](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)"}
{"_id": 157, "title": "", "text": "```java int[] num = new int[5];
An *array* is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the `main` method of the \"Hello World!\" application. This section discusses arrays in greater detail.
Each item in an array is called an *element*, and each element is accessed by its numerical *index*. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
The following program, [`ArrayDemo`](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/examples/ArrayDemo.java), creates an array of integers, puts some values in the array, and prints each value to standard output.
`class ArrayDemo { public static void main(String[] args) { // declares an array of integers int[] anArray;
// allocates memory for 10 integers anArray = new int[10];
// initialize first element anArray[0] = 100; // initialize second element anArray[1] = 200; // and so forth anArray[2] = 300; anArray[3] = 400; anArray[4] = 500; anArray[5] = 600; anArray[6] = 700; anArray[7] = 800; anArray[8] = 900; anArray[9] = 1000;
System.out.println(\"Element at index 0: \" + anArray[0]); System.out.println(\"Element at index 1: \" + anArray[1]); System.out.println(\"Element at index 2: \" + anArray[2]); System.out.println(\"Element at index 3: \" + anArray[3]); System.out.println(\"Element at index 4: \" + anArray[4]); System.out.println(\"Element at index 5: \" + anArray[5]); System.out.println(\"Element at index 6: \" + anArray[6]); System.out.println(\"Element at index 7: \" + anArray[7]); System.out.println(\"Element at index 8: \" + anArray[8]); System.out.println(\"Element at index 9: \" + anArray[9]); } }`
The output from this program is:
`Element at index 0: 100 Element at index 1: 200 Element at index 2: 300 Element at index 3: 400 Element at index 4: 500 Element at index 5: 600 Element at index 6: 700 Element at index 7: 800 Element at index 8: 900 Element at index 9: 1000`
In a real-world programming situation, you would probably use one of the supported *looping constructs* to iterate through each element of the array, rather than write each line individually as in the preceding example. However, the example clearly illustrates the array syntax. You will learn about the various looping constructs (`for`, `while`, and `do-while`) in the [Control Flow](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html) section."}
{"_id": 159, "title": "", "text": "```java String myString = \"1234\"; int foo = Integer.parseInt(myString);
```
If you look at the [Java documentation](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Integer.html#parseInt(java.lang.String)) you'll notice the \"catch\" is that this function can throw a `NumberFormatException`, which you can handle:
(This treatment defaults a malformed number to `0`, but you can do something else if you like.)
Alternatively, you can use an `Ints` method from the Guava library, which in combination with Java 8's `Optional`, makes for a powerful and concise way to convert a string into an int:
``` public static int parseInt(String s) throwsNumberFormatException ```
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign `'-'` (`'\\u002D'`) to indicate a negative value or an ASCII plus sign `'+'` (`'\\u002B'`) to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the [`parseInt(java.lang.String, int)`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Integer.html#parseInt(java.lang.String,int)) method.
**Parameters:**`s` - a `String` containing the `int` representation to be parsed**Returns:**the integer value represented by the argument in decimal.**Throws:**[`NumberFormatException`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/NumberFormatException.html) - if the string does not contain a parsable integer."}
{"_id": 162, "title": "", "text": "My favorite way to read a small file is to use a BufferedReader and a StringBuilder. It is very simple and to the point (though not particularly effective, but good enough for most cases):
BufferedReader br = new BufferedReader(new FileReader(\"file.txt\")); try { StringBuilder sb = new StringBuilder(); String line = br.readLine();
while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String everything = sb.toString(); } finally { br.close(); } Some has pointed out that after Java 7 you should use try-with-resources (i.e. auto close) features:
try(BufferedReader br = new BufferedReader(new FileReader(\"file.txt\"))) { StringBuilder sb = new StringBuilder(); String line = br.readLine();
while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String everything = sb.toString(); } When I read strings like this, I usually want to do some string handling per line anyways, so then I go for this implementation.
Though if I want to actually just read a file into a String, I always use Apache Commons IO with the class IOUtils.toString() method. You can have a look at the source here:
The `try`-with-resources statement is a `try` statement that declares one or more resources. A *resource* is an object that must be closed after the program is finished with it. The `try`-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements `java.lang.AutoCloseable`, which includes all objects which implement `java.io.Closeable`, can be used as a resource.
The following example reads the first line from a file. It uses an instance of `FileReader` and `BufferedReader` to read data from the file. `FileReader` and `BufferedReader` are resources that must be closed after the program is finished with it:
In this example, the resources declared in the `try`-with-resources statement are a `FileReader` and a `BufferedReader`. The declaration statements of these resources appear within parentheses immediately after the `try` keyword. The classes `FileReader` and `BufferedReader`, in Java SE 7 and later, implement the interface `java.lang.AutoCloseable`. Because the `FileReader` and `BufferedReader` instances are declared in a `try`-with-resource statement, they will be closed regardless of whether the `try` statement completes normally or abruptly (as a result of the method `BufferedReader.readLine` throwing an `IOException`).
Prior to Java SE 7, you can use a `finally` block to ensure that a resource is closed regardless of whether the `try` statement completes normally or abruptly. The following example uses a `finally` block instead of a `try`-with-resources statement:
FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); try { return br.readLine(); } finally { br.close(); fr.close(); } }`"}
{"_id": 165, "title": "", "text": "*Note that each of the code samples below may throw `IOException`. Try/catch/finally blocks have been omitted for brevity. See [this tutorial](https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html) for information about exception handling.*
*Note that each of the code samples below will overwrite the file if it already exists*
Creating a text file:
```java PrintWriter writer = new PrintWriter(\"the-file-name.txt\", \"UTF-8\"); writer.println(\"The first line\"); writer.println(\"The second line\"); writer.close();
```
Creating a binary file:
```java byte data[] = ... FileOutputStream out = new FileOutputStream(\"the-file-name\"); out.write(data); out.close();
```
**Java 7+** users can use the [`Files`](http://docs.oracle.com/javase/7/docs/api/index.html?java/nio/file/Files.html) class to write to files:
Creating a text file:
```java List lines = Arrays.asList(\"The first line\", \"The second line\"); Path file = Paths.get(\"the-file-name.txt\"); Files.write(file, lines, StandardCharsets.UTF_8); //Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
- newInputStreamOpens a file, returning an input stream to read from the file. The stream will not be buffered, and is not required to support the [`mark`](https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#mark(int)) or [`reset`](https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#reset()) methods. The stream will be safe for access by multiple concurrent threads. Reading commences at the beginning of the file. Whether the returned stream is *asynchronously closeable* and/or *interruptible* is highly file system provider specific and therefore not specified.
``` public staticInputStream newInputStream(Path path, OpenOption... options) throwsIOException ```
The `options` parameter determines how the file is opened. If no options are present then it is equivalent to opening the file with the [`READ`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#READ) option. In addition to the `READ` option, an implementation may also support additional implementation specific options.
**Parameters:**`path` - the path to the file to open`options` - options specifying how the file is opened**Returns:**a new input stream**Throws:**[`IllegalArgumentException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html) - if an invalid combination of options is specified[`UnsupportedOperationException`](https://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html) - if an unsupported option is specified[`IOException`](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) - if an I/O error occurs[`SecurityException`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityException.html) - In the case of the default provider, and a security manager is installed, the [`checkRead`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkRead(java.lang.String)) method is invoked to check read access to the file.
- newOutputStreamOpens or creates a file, returning an output stream that may be used to write bytes to the file. The resulting stream will not be buffered. The stream will be safe for access by multiple concurrent threads. Whether the returned stream is *asynchronously closeable* and/or *interruptible* is highly file system provider specific and therefore not specified.
``` public staticOutputStream newOutputStream(Path path, OpenOption... options) throwsIOException ```
This method opens or creates a file in exactly the manner specified by the [`newByteChannel`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newByteChannel(java.nio.file.Path,%20java.util.Set,%20java.nio.file.attribute.FileAttribute...)) method with the exception that the [`READ`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#READ) option may not be present in the array of options. If no options are present then this method works as if the [`CREATE`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#CREATE), [`TRUNCATE_EXISTING`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#TRUNCATE_EXISTING), and [`WRITE`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardOpenOption.html#WRITE) options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing [`regular-file`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#isRegularFile(java.nio.file.Path,%20java.nio.file.LinkOption...)) to a size of `0` if it exists.
**Usage Examples:**
``` Path path = ...
// truncate and overwrite an existing file, or create the file if // it doesn't initially exist OutputStream out = Files.newOutputStream(path);
// append to an existing file, fail if the file does not exist out = Files.newOutputStream(path, APPEND);
// append to an existing file, create file if it doesn't initially exist out = Files.newOutputStream(path, CREATE, APPEND);
// always create new file, failing if it already exists out = Files.newOutputStream(path, CREATE_NEW);
```
**Parameters:**`path` - the path to the file to open or create`options` - options specifying how the file is opened**Returns:**a new output stream**Throws:**[`IllegalArgumentException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html) - if `options` contains an invalid combination of options[`UnsupportedOperationException`](https://docs.oracle.com/javase/7/docs/api/java/lang/UnsupportedOperationException.html) - if an unsupported option is specified[`IOException`](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) - if an I/O error occurs[`SecurityException`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityException.html) - In the case of the default provider, and a security manager is installed, the [`checkWrite`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkWrite(java.lang.String)) method is invoked to check write access to the file. The [`checkDelete`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkDelete(java.lang.String)) method is invoked to check delete access if the file is opened with the `DELETE_ON_CLOSE` option."}
{"_id": 168, "title": "", "text": "Use [`LocalDateTime#parse()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDateTime.html#parse(java.lang.CharSequence,java.time.format.DateTimeFormatter)) (or [`ZonedDateTime#parse()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/ZonedDateTime.html#parse(java.lang.CharSequence,java.time.format.DateTimeFormatter)) if the string happens to contain a time zone part) to parse a `String` in a certain pattern into a `LocalDateTime`.
Then use [`LocalDateTime#format()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDateTime.html#format(java.time.format.DateTimeFormatter)) (or [`ZonedDateTime#format()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/ZonedDateTime.html#format(java.time.format.DateTimeFormatter))) to format a `LocalDateTime` into a `String` in a certain pattern.
**Or**, when you're not on Java 8 yet, use [`SimpleDateFormat#parse()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/DateFormat.html#parse(java.lang.String)) to parse a `String` in a certain pattern into a `Date`.
```java String oldstring = \"2011-01-18 00:00:00.0\"; Date date = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss.S\").parse(oldstring);
```
Then use [`SimpleDateFormat#format()`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/DateFormat.html#format(java.util.Date)) to format a `Date` into a `String` in a certain pattern.
```java String newstring = new SimpleDateFormat(\"yyyy-MM-dd\").format(date); System.out.println(newstring); // 2011-01-18
```
### See also:
- [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion/)
---
**Update**: as per your failed attempt which you added to the question after this answer was posted; the patterns are **case sensitive**. Carefully read the [`java.text.SimpleDateFormat` javadoc](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/text/SimpleDateFormat.html) what the individual parts stands for. So stands for example `M` for months and `m` for minutes. Also, years exist of four digits `yyyy`, not five `yyyyy`. Look closer at the code snippets I posted here above."}
{"_id": 169, "title": "", "text": "```java String oldstring = \"2011-01-18 00:00:00.0\"; LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss.S\"));
```"}
{"_id": 170, "title": "", "text": "- parseObtains an instance of `LocalDateTime` from a text string using a specific formatter.
public static [LocalDateTime](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/LocalDateTime.html) parse([CharSequence](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/CharSequence.html) text, [DateTimeFormatter](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html) formatter)
The text is parsed using the formatter, returning a date-time.
**Parameters:**`text` - the text to parse, not null`formatter` - the formatter to use, not null**Returns:**the parsed local date-time, not null**Throws:**[`DateTimeParseException`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeParseException.html) - if the text cannot be parsed"}
{"_id": 171, "title": "", "text": "## Read all text from a file
Java 11 added the [readString()](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path,java.nio.charset.Charset)) method to read small files as a `String`, preserving line terminators:
Java 7 added a [convenience method to read a file as lines of text,](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines%28java.nio.file.Path,%20java.nio.charset.Charset%29) represented as a `List`. This approach is \"lossy\" because the line separators are stripped from the end of each line.
```java List lines = Files.readAllLines(Paths.get(path), encoding);
```
Java 8 added the [`Files.lines()`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-java.nio.charset.Charset-) method to produce a `Stream`. Again, this method is lossy because line separators are stripped. If an `IOException` is encountered while reading the file, it is wrapped in an [`UncheckedIOException`](https://docs.oracle.com/javase/8/docs/api/java/io/UncheckedIOException.html), since `Stream` doesn't accept lambdas that throw checked exceptions.
This `Stream` does need a [`close()`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/BaseStream.html#close--) call; this is poorly documented on the API, and I suspect many people don't even notice `Stream` has a `close()` method. Be sure to use an ARM-block as shown.
If you are working with a source other than a file, you can use the [`lines()`](https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#lines--) method in `BufferedReader` instead.
## Memory utilization
If your file is small enough relative to your available memory, reading the entire file at once might work fine. However, if your file is too large, reading one line at a time, processing it, and then discarding it before moving on to the next could be a better approach. Stream processing in this way can eliminate the total file size as a factor in your memory requirement.
## Character encoding
One thing that is missing from the sample in the original post is the character encoding. This encoding generally can't be determined from the file itself, and requires meta-data such as an HTTP header to convey this important information.
The [`StandardCharsets`](https://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html) class defines some constants for the encodings required of all Java runtimes:
The platform default is available from [the `Charset` class](https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html#defaultCharset%28%29) itself:
There are some special cases where the platform default is what you want, but they are rare. You should be able justify your choice, because the platform default is not portable. One example where it might be correct is when reading standard input or writing standard output.
---
Note: This answer largely replaces my Java 6 version. The utility of Java 7 safely simplifies the code, and the old answer, which used a mapped byte buffer, prevented the file that was read from being deleted until the mapped buffer was garbage collected. You can view the old version via the \"edited\" link on this answer."}
{"_id": 172, "title": "", "text": "```java try (Stream lines = Files.lines(path, encoding)) { lines.forEach(System.out::println); }
. The method ensures that the file is closed when all content have been read or an I/O error, or other runtime exception, is thrown.
This method reads all content including the line separators in the middle and/or at the end. The resulting string will contain line separators as they appear in the file.
**API Note:**This method is intended for simple cases where it is appropriate and convenient to read the content of a file into a String. It is not intended for reading very large files.**Parameters:**`path` - the path to the file`cs` - the charset to use for decoding**Returns:**a String containing the content read from the file**Throws:**[`IOException`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/IOException.html) - if an I/O error occurs reading from the file or a malformed or unmappable byte sequence is read[`OutOfMemoryError`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/OutOfMemoryError.html) - if the file is extremely large, for example larger than `2GB[SecurityException](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/SecurityException.html)` - In the case of the default provider, and a security manager is installed, the [`checkRead`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/SecurityManager.html#checkRead(java.lang.String)) method is invoked to check read access to the file.**Since:**11"}
{"_id": 174, "title": "", "text": "ou can use the [`java.lang.instrument` package](http://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html).
- addTransformerRegisters the supplied transformer. All future class definitions will be seen by the transformer, except definitions of classes upon which any registered transformer is dependent. The transformer is called when classes are loaded, when they are [redefined](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html#redefineClasses-java.lang.instrument.ClassDefinition...-). and if `canRetransform` is true, when they are [retransformed](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html#retransformClasses-java.lang.Class...-). See [`ClassFileTransformer.transform`](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/ClassFileTransformer.html#transform-java.lang.ClassLoader-java.lang.String-java.lang.Class-java.security.ProtectionDomain-byte:A-) for the order of transform calls. If a transformer throws an exception during execution, the JVM will still call the other registered transformers in order. The same transformer may be added more than once, but it is strongly discouraged -- avoid this by creating a new instance of transformer class.
This method is intended for use in instrumentation, as described in the [class specification](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html).
**Parameters:**`transformer` - the transformer to register`canRetransform` - can this transformer's transformations be retransformed**Throws:**[`NullPointerException`](https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html) - if passed a `null` transformer[`UnsupportedOperationException`](https://docs.oracle.com/javase/8/docs/api/java/lang/UnsupportedOperationException.html) - if `canRetransform` is true and the current configuration of the JVM does not allow retransformation ([`isRetransformClassesSupported()`](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html#isRetransformClassesSupported--) is false)**Since:**1.6"}
{"_id": 177, "title": "", "text": "Coding from the hip, it would be something like:
The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give `methodName`).
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.
**Extensibility Features**An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.**Class Browsers and Visual Development Environments**A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.**Debuggers and Test Tools**Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.
## **Drawbacks of Reflection**
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.
**Performance Overhead**Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.**Security Restrictions**Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.**Exposure of Internals**Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing `private` fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform."}
{"_id": 180, "title": "", "text": "Yes, it is a shorthand form of
```java int count; if (isHere) count = getHereCount(index); else count = getAwayCount(index);
```
It's called the **conditional operator**. Many people (erroneously) call it *the ternary operator*, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there *could* be another ternary operator, whereas there can only be one *conditional operator*.
The official name is given in the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25):
> §15.25 Conditional Operator ? : > > > The conditional operator `? :` uses the boolean value of one expression to decide which of two other expressions should be evaluated. >
Note that both branches must lead to methods with return values:
> It is a compile-time error for either the second or the third operand expression to be an invocation of a void method. > > > *In fact, by the grammar of expression statements ([§14.8](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.8)), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.* >
So, if `doSomething()` and `doSomethingElse()` are void methods, you cannot compress this:
```java if (someBool) doSomething(); else doSomethingElse();
The conditional operator is syntactically right-associative (it groups right-to-left). Thus, `a?b:c?d:e?f:g` means the same as `a?b:(c?d:(e?f:g))`.
The conditional operator has three operand expressions. `?` appears between the first and second expressions, and `:` appears between the second and third expressions.
**The first expression must be of type `boolean` or `Boolean`, or a compile-time error occurs.**
**It is a compile-time error for either the second or the third operand expression to be an invocation of a `void` method.**
*In fact, by the grammar of expression statements ([§14.8](https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.8)), it is not permitted for a conditional expression to appear in any context where an invocation of a `void` method could appear.*
There are three kinds of conditional expressions, classified according to the second and third operand expressions: *boolean conditional expressions*, *numeric conditional expressions*, and *reference conditional expressions*. The classification rules are as follows:
- If both the second and the third operand expressions are *boolean expressions*, the conditional expression is a boolean conditional expression.
For the purpose of classifying a conditional, the following expressions are boolean expressions:
- An expression of a standalone form ([§15.2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.2)) that has type `boolean` or `Boolean`. - A parenthesized `boolean` expression ([§15.8.5](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.5)). - A class instance creation expression ([§15.9](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.9)) for class `Boolean`. - A method invocation expression ([§15.12](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12)) for which the chosen most specific method ([§15.12.2.5](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.5)) has return type `boolean` or `Boolean`.
*Note that, for a generic method, this is the type before instantiating the method's type arguments.*
- A `boolean` conditional expression. - If both the second and the third operand expressions are *numeric expressions*, the conditional expression is a numeric conditional expression.
For the purpose of classifying a conditional, the following expressions are numeric expressions:
- An expression of a standalone form ([§15.2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.2)) with a type that is convertible to a numeric type ([§4.2](https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2), [§5.1.8](https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.8)). - A parenthesized numeric expression ([§15.8.5](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.8.5)). - A class instance creation expression ([§15.9](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.9)) for a class that is convertible to a numeric type. - A method invocation expression ([§15.12](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12)) for which the chosen most specific method ([§15.12.2.5](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2.5)) has a return type that is convertible to a numeric type. - A numeric conditional expression. - Otherwise, the conditional expression is a reference conditional expression.
The process for determining the type of a conditional expression depends on the kind of conditional expression, as outlined in the following sections."}
{"_id": 183, "title": "", "text": "By an \"anonymous class\", I take it you mean [anonymous inner class](http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html).
An anonymous inner class can come useful when making an instance of an object with certain \"extras\" such as overriding methods, without having to actually subclass a class.
I tend to use it as a shortcut for attaching an event listener:
```java button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // do something } });
```
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements `ActionListener` -- I can just instantiate an anonymous inner class without actually making a separate class.
I only use this technique for \"quick and dirty\" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class."}
{"_id": 184, "title": "", "text": "```java button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // do something } });
```"}
{"_id": 185, "title": "", "text": "# **Inner Class Example**
To see an inner class in use, first consider an array. In the following example, you create an array, fill it with integer values, and then output only values of even indices of the array in ascending order.
The [`DataStructure.java`](https://docs.oracle.com/javase/tutorial/java/javaOO/examples/DataStructure.java) example that follows consists of:
- The `DataStructure` outer class, which includes a constructor to create an instance of `DataStructure` containing an array filled with consecutive integer values (0, 1, 2, 3, and so on) and a method that prints elements of the array that have an even index value. - The `EvenIterator` inner class, which implements the `DataStructureIterator` interface, which extends the [`Iterator](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)<` [`Integer](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html)>` interface. Iterators are used to step through a data structure and typically have methods to test for the last element, retrieve the current element, and move to the next element. - A `main` method that instantiates a `DataStructure` object (`ds`), then invokes the `printEven` method to print elements of the array `arrayOfInts` that have an even index value.
`public class DataStructure {
// Create an array private final static int SIZE = 15; private int[] arrayOfInts = new int[SIZE];
public DataStructure() { // fill the array with ascending integer values for (int i = 0; i < SIZE; i++) { arrayOfInts[i] = i; } }
public void printEven() {
// Print out values of even indices of the array DataStructureIterator iterator = this.new EvenIterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + \" \"); } System.out.println(); }
// Inner class implements the DataStructureIterator interface, // which extends the Iterator interface
private class EvenIterator implements DataStructureIterator {
// Start stepping through the array from the beginning private int nextIndex = 0;
public boolean hasNext() {
// Check if the current element is the last in the array return (nextIndex <= SIZE - 1); }
public Integer next() {
// Record a value of an even index of the array Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]);
// Get the next even element nextIndex += 2; return retValue; } }
public static void main(String s[]) {
// Fill the array with integer values and print out only // values of even indices DataStructure ds = new DataStructure(); ds.printEven(); } }`
The output is:
`0 2 4 6 8 10 12 14`"}
{"_id": 186, "title": "", "text": "A common pattern is to use
```java try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { // process the line. } }
```
You can read the data faster if you assume there is no character encoding. e.g. ASCII-7 but it won't make much difference. It is highly likely that what you do with the data will take much longer.
EDIT: A less common pattern to use which avoids the scope of `line` leaking.
```java try(BufferedReader br = new BufferedReader(new FileReader(file))) { for(String line; (line = br.readLine()) != null; ) { // process the line. } // line is not visible here. }
NOTE: You have to place the Stream in a [try-with-resource](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) block to ensure the #close method is called on it, otherwise the underlying file handle is never closed until GC does it much later."}
{"_id": 187, "title": "", "text": "```java try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { // process the line. } }
The `try`-with-resources statement is a `try` statement that declares one or more resources. A *resource* is an object that must be closed after the program is finished with it. The `try`-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements `java.lang.AutoCloseable`, which includes all objects which implement `java.io.Closeable`, can be used as a resource.
The following example reads the first line from a file. It uses an instance of `FileReader` and `BufferedReader` to read data from the file. `FileReader` and `BufferedReader` are resources that must be closed after the program is finished with it:
In this example, the resources declared in the `try`-with-resources statement are a `FileReader` and a `BufferedReader`. The declaration statements of these resources appear within parentheses immediately after the `try` keyword. The classes `FileReader` and `BufferedReader`, in Java SE 7 and later, implement the interface `java.lang.AutoCloseable`. Because the `FileReader` and `BufferedReader` instances are declared in a `try`-with-resource statement, they will be closed regardless of whether the `try` statement completes normally or abruptly (as a result of the method `BufferedReader.readLine` throwing an `IOException`).
Prior to Java SE 7, you can use a `finally` block to ensure that a resource is closed regardless of whether the `try` statement completes normally or abruptly. The following example uses a `finally` block instead of a `try`-with-resources statement:
However, this example might have a resource leak. A program has to do more than rely on the garbage collector (GC) to reclaim a resource's memory when it's finished with it. The program must also release the resoure back to the operating system, typically by calling the resource's `close` method. However, if a program fails to do this before the GC reclaims the resource, then the information needed to release the resource is lost. The resource, which is still considered by the operaing system to be in use, has leaked."}
{"_id": 189, "title": "", "text": "You can use the ScriptEngine class and evaluate it as a Javascript string. ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(\"js\"); Object result = engine.eval(\"4*5\");
There may be a better way, but this one works."}
{"_id": 190, "title": "", "text": "```java ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(\"js\"); Object result = engine.eval(\"4*5\");
- **All Known Implementing Classes:**[AbstractScriptEngine](https://docs.oracle.com/javase/8/docs/api/javax/script/AbstractScriptEngine.html)
---
``` public interfaceScriptEngine ```
`ScriptEngine` is the fundamental interface whose methods must be fully functional in every implementation of this specification.These methods provide basic scripting functionality. Applications written to this simple interface are expected to work with minimal modifications in every implementation. It includes methods that execute scripts, and ones that set and get values.The values are key/value pairs of two types. The first type of pairs consists of those whose keys are reserved and defined in this specification or by individual implementations. The values in the pairs with reserved keys have specified meanings.The other type of pairs consists of those that create Java language Bindings, the values are usually represented in scripts by the corresponding keys or by decorated forms of them.
**Since:**1.6"}
{"_id": 192, "title": "", "text": "From the [`Object.toString`](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#toString%28%29) docs:
> Returns a string representation of the object. In general, the toString method returns a string that \"textually represents\" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method. > > > The `toString` method for class `Object` returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of: >
Returns a string representation of the object. In general, the `toString` method returns a string that \"textually represents\" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method. The `toString` method for class `Object` returns a string consisting of the name of the class of which the object is an instance, the at-sign character ``@`', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
**Returns:**a string representation of the object."}
{"_id": 195, "title": "", "text": "As of **Java 8**, there is an officially supported API for Base64 encoding and decoding. In time this will probably become the default choice.
The API includes the class [`java.util.Base64`](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html) and its nested classes. It supports three different flavors: basic, URL safe, and MIME.
The [documentation for `java.util.Base64`](https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html) includes several more methods for configuring encoders and decoders, and for using different classes as inputs and outputs (byte arrays, strings, ByteBuffers, java.io streams)."}
{"_id": 196, "title": "", "text": "```java import java.util.Base64;
```"}
{"_id": 197, "title": "", "text": "## Class Base64
- [java.lang.Object](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html) - java.util.Base64 - This class consists exclusively of static methods for obtaining encoders and decoders for the Base64 encoding scheme. The implementation of this class supports the following types of Base64 as specified in [RFC 4648](http://www.ietf.org/rfc/rfc4648.txt) and [RFC 2045](http://www.ietf.org/rfc/rfc2045.txt).
``` public classBase64 extendsObject ```
- **Basic**
Uses \"The Base64 Alphabet\" as specified in Table 1 of RFC 4648 and RFC 2045 for encoding and decoding operation. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.
- **URL and Filename safe**
Uses the \"URL and Filename safe Base64 Alphabet\" as specified in Table 2 of RFC 4648 for encoding and decoding. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.
- **MIME**
Uses the \"The Base64 Alphabet\" as specified in Table 1 of RFC 2045 for encoding and decoding operation. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return `'\\r'` followed immediately by a linefeed `'\\n'` as the line separator. No line separator is added to the end of the encoded output. All line separators or other characters not found in the base64 alphabet table are ignored in decoding operation.
Unless otherwise noted, passing a `null` argument to a method of this class will cause a [`NullPointerException`](https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html) to be thrown.
**Since:**1.8"}
{"_id": 198, "title": "", "text": "In Java 8 you can use the [`Supplier`](https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html) functional interface to achieve this pretty easily:
```java class SomeContainer { private Supplier supplier;
- **Type Parameters:**`T` - the type of results supplied by this supplierRepresents a supplier of results.
**Functional Interface:**This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
---
``` @FunctionalInterface public interfaceSupplier ```
There is no requirement that a new or distinct result be returned each time the supplier is invoked.
This is a [functional interface](https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html) whose functional method is [`get()`](https://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html#get--).
**Since:**1.8"}
{"_id": 201, "title": "", "text": "Straight from the API Specifications for the [`ClassCastException`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassCastException.html):
> Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. >
So, for example, when one tries to cast an `Integer` to a `String`, `String` is not an subclass of `Integer`, so a `ClassCastException` will be thrown.
```java Object i = Integer.valueOf(42); String s = (String)i; // ClassCastException thrown ```"}
{"_id": 202, "title": "", "text": "```java Object i = Integer.valueOf(42); String s = (String)i; // ClassCastException thrown ```"}
{"_id": 203, "title": "", "text": "## Class ClassCastException
`public class **ClassCastException**extends [RuntimeException](https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/RuntimeException.html)`
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a `ClassCastException`:
> Object x = new Integer(0); System.out.println((String)x); >
---"}
{"_id": 204, "title": "", "text": "A simple example to illustrate how `java.util.Scanner` works would be reading a single integer from `System.in`. It's really quite simple.
```java Scanner sc = new Scanner(System.in); int i = sc.nextInt();
```
To retrieve a username I would probably use [`sc.nextLine()`](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine%28%29).
```java System.out.println(\"Enter your username: \"); Scanner scanner = new Scanner(System.in); String username = scanner.nextLine(); System.out.println(\"Your username is \" + username);
```
You could also use [`next(String pattern)`](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next%28java.lang.String%29) if you want more control over the input, or just validate the `username` variable.
You'll find more information on their implementation in the [API Documentation for `java.util.Scanner`](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)"}
{"_id": 205, "title": "", "text": "```java System.out.println(\"Enter your username: \"); Scanner scanner = new Scanner(System.in); String username = scanner.nextLine(); System.out.println(\"Your username is \" + username);
```"}
{"_id": 206, "title": "", "text": "- nextLineAdvances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
``` publicString nextLine() ```
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
**Returns:**the line that was skipped**Throws:**[`NoSuchElementException`](https://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html) - if no line was found[`IllegalStateException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalStateException.html) - if this scanner is closed"}
{"_id": 207, "title": "", "text": "- Add each number in the range sequentially in a [list](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/List.html) structure. - [Shuffle](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Collections.html#shuffle(java.util.List)) it. - Take the first 'n'.
Here is a simple implementation. This will print 3 unique random numbers from the range 1-10.
public static void main(String[] args) { ArrayList list = new ArrayList(); for (int i=1; i<11; i++) list.add(i); Collections.shuffle(list); for (int i=0; i<3; i++) System.out.println(list.get(i)); } }
```
---
The first part of the fix with the original approach, as Mark Byers pointed out in an answer now deleted, is to use only a single `Random` instance.
That is what is causing the numbers to be identical. A `Random` instance is seeded by the current time in milliseconds. For a particular **seed value,** the 'random' instance will return the exact same **sequence of *pseudo random* numbers.**"}
{"_id": 208, "title": "", "text": "```java import java.util.ArrayList; import java.util.Collections;
public class UniqueRandomNumbers {
public static void main(String[] args) { ArrayList list = new ArrayList(); for (int i=1; i<11; i++) list.add(i); Collections.shuffle(list); for (int i=0; i<3; i++) System.out.println(list.get(i)); } }
Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.
The hedge \"approximately\" is used in the foregoing description because default source of randomness is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm would choose permutations with perfect uniformity.
This implementation traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the \"current position\". Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.
This method runs in linear time. If the specified list does not implement the [`RandomAccess`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/RandomAccess.html) interface and is large, this implementation dumps the specified list into an array before shuffling it, and dumps the shuffled array back into the list. This avoids the quadratic behavior that would result from shuffling a \"sequential access\" list in place.
**Parameters:**`list` - the list to be shuffled.**Throws:**[`UnsupportedOperationException`](https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/UnsupportedOperationException.html) - if the specified list or its list-iterator does not support the `set` operation."}
{"_id": 210, "title": "", "text": "**Code :**
```java public class JavaApplication { public static void main(String[] args) { System.out.println(\"Working Directory = \" + System.getProperty(\"user.dir\")); } }
```
*This will print the absolute path of the current directory from where your application was initialized.*
---
**Explanation:**
From the [documentation](https://docs.oracle.com/javase/7/docs/api/java/io/File.html):
`java.io` package resolve relative pathnames using current user directory. The current directory is represented as system property, that is, `user.dir` and is the directory from where the JVM was invoked."}
{"_id": 211, "title": "", "text": "```java public class JavaApplication { public static void main(String[] args) { System.out.println(\"Working Directory = \" + System.getProperty(\"user.dir\")); } }
```"}
{"_id": 212, "title": "", "text": "java.io
## Class File
- [java.lang.Object](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html) - java.io.File - **All Implemented Interfaces:**[Serializable](https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html), [Comparable](https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html)<[File](https://docs.oracle.com/javase/7/docs/api/java/io/File.html)>An abstract representation of file and directory pathnames.The first name in an abstract pathname may be a directory name or, in the case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name in an abstract pathname denotes a directory; the last name may denote either a directory or a file. The *empty* abstract pathname has no prefix and an empty name sequence.
---
``` public classFile extendsObject implementsSerializable,Comparable ```
User interfaces and operating systems use system-dependent *pathname strings* to name files and directories. This class presents an abstract, system-independent view of hierarchical pathnames. An *abstract pathname* has two components:
1. An optional system-dependent *prefix* string, such as a disk-drive specifier, `\"/\"` for the UNIX root directory, or `\"\\\\\\\\\"` for a Microsoft Windows UNC pathname, and 2. A sequence of zero or more string *names*.
The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default *separator character*. The default name-separator character is defined by the system property `file.separator`, and is made available in the public static fields [`separator`](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#separator) and [`separatorChar`](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#separatorChar) of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system.
A pathname, whether abstract or in string form, may be either *absolute* or *relative*. An absolute pathname is complete in that no other information is required in order to locate the file that it denotes. A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the `java.io` package always resolve relative pathnames against the current user directory. This directory is named by the system property `user.dir`, and is typically the directory in which the Java virtual machine was invoked.
The *parent* of an abstract pathname may be obtained by invoking the [`getParent()`](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#getParent()) method of this class and consists of the pathname's prefix and each name in the pathname's name sequence except for the last. Each directory's absolute pathname is an ancestor of any File object with an absolute abstract pathname which begins with the directory's absolute pathname. For example, the directory denoted by the abstract pathname \"/usr\" is an ancestor of the directory denoted by the pathname \"/usr/local/bin\".
The prefix concept is used to handle root directories on UNIX platforms, and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms, as follows:
- For UNIX platforms, the prefix of an absolute pathname is always `\"/\"`. Relative pathnames have no prefix. The abstract pathname denoting the root directory has the prefix `\"/\"` and an empty name sequence. - For Microsoft Windows platforms, the prefix of a pathname that contains a drive specifier consists of the drive letter followed by `\":\"` and possibly followed by `\"\\\\\"` if the pathname is absolute. The prefix of a UNC pathname is `\"\\\\\\\\\"`; the hostname and the share name are the first two names in the name sequence. A relative pathname that does not specify a drive has no prefix.
Instances of this class may or may not denote an actual file-system object such as a file or a directory. If it does denote such an object then that object resides in a *partition*. A partition is an operating system-specific portion of storage for a file system. A single storage device (e.g. a physical disk-drive, flash memory, CD-ROM) may contain multiple partitions. The object, if any, will reside on the partition named by some ancestor of the absolute form of this pathname.
A file system may implement restrictions to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are collectively known as *access permissions*. The file system may have multiple sets of access permissions on a single object. For example, one set may apply to the object's *owner*, and another may apply to all other users. The access permissions on an object may cause some methods in this class to fail.
Instances of the `File` class are immutable; that is, once created, the abstract pathname represented by a `File` object will never change.
### Interoperability with `java.nio.file` package
The [`java.nio.file`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/package-summary.html) package defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems. This API may be used to overcome many of the limitations of the `java.io.File` class. The [`toPath`](https://docs.oracle.com/javase/7/docs/api/java/io/File.html#toPath()) method may be used to obtain a [`Path`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html) that uses the abstract path represented by a `File` object to locate a file. The resulting `Path` may be used with the [`Files`](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) class to provide more efficient and extensive access to additional file operations, file attributes, and I/O exceptions to help diagnose errors when an operation on a file fails.
**Since:**JDK1.0**See Also:**[Serialized Form](https://docs.oracle.com/javase/7/docs/api/serialized-form.html#java.io.File)"}
{"_id": 213, "title": "", "text": "Java 8 ([2014](https://www.oracle.com/java/technologies/javase/8-whats-new.html)) solves this problem using streams and lambdas in one line of code:
```java List beerDrinkers = persons.stream() .filter(p -> p.getAge() > 16).collect(Collectors.toList());
```
Here's a [tutorial](http://zeroturnaround.com/rebellabs/java-8-explained-applying-lambdas-to-java-collections/).
Use [`Collection#removeIf`](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-) to modify the collection in place. (Notice: In this case, the predicate will remove objects who satisfy the predicate):
```java persons.removeIf(p -> p.getAge() <= 16);
```
---
[lambdaj](https://code.google.com/archive/p/lambdaj/) allows filtering collections without writing loops or inner classes:
```java List beerDrinkers = select(persons, having(on(Person.class).getAge(), greaterThan(16)));
```
Can you imagine something more readable?
**Disclaimer:** I am a contributor on lambdaj"}
{"_id": 214, "title": "", "text": "```java List beerDrinkers = persons.stream() .filter(p -> p.getAge() > 16).collect(Collectors.toList());
Removes all of the elements of this collection that satisfy the given predicate. Errors or runtime exceptions thrown during iteration or by the predicate are relayed to the caller.
**Implementation Requirements:**The default implementation traverses all elements of the collection using its [`iterator()`](https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#iterator--). Each matching element is removed using [`Iterator.remove()`](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#remove--). If the collection's iterator does not support removal then an `UnsupportedOperationException` will be thrown on the first matching element.**Parameters:**`filter` - a predicate which returns `true` for elements to be removed**Returns:**`true` if any elements were removed**Throws:**[`NullPointerException`](https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html) - if the specified filter is null[`UnsupportedOperationException`](https://docs.oracle.com/javase/8/docs/api/java/lang/UnsupportedOperationException.html) - if elements cannot be removed from this collection. Implementations may throw this exception if a matching element cannot be removed or if, in general, removal is not supported.**Since:**1.8"}
{"_id": 216, "title": "", "text": "see https://stackoverflow.com/a/20906602/314283
Java does appear to be well behind the eight-ball compared to C#. This utility method shows the way to do in Java SE 6 using the [Calendar.add method](http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#add%28int,%20int%29) (presumably the only easy way).
```java public class DateUtil { public static Date addDays(Date date, int days) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, days); //minus number would decrement the days return cal.getTime(); } }
```
To add one day, per the question asked, call it as follows:
```java String sourceDate = \"2012-02-29\"; SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\"); Date myDate = format.parse(sourceDate); myDate = DateUtil.addDays(myDate, 1); ```"}
{"_id": 217, "title": "", "text": "```java String sourceDate = \"2012-02-29\"; SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\"); Date myDate = format.parse(sourceDate); myDate = DateUtil.addDays(myDate, 1); ```"}
{"_id": 218, "title": "", "text": "### add
``` public abstract voidadd(int field, int amount) ```
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:`add(Calendar.DAY_OF_MONTH, -5)`. **Parameters:**`field` - the calendar field.`amount` - the amount of date or time to be added to the field.**See Also:**[`roll(int,int)`](https://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#roll(int,%20int)), [`set(int,int)`](https://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html#set(int,%20int))"}
{"_id": 219, "title": "", "text": "You could use `printf()` with `%f`:
0 in `%.0f` means 0 places in fractional part i.e no fractional part. If you want to print fractional part with desired number of decimal places then instead of 0 just provide the number like this `%.8f`. By default fractional part is printed up to 6 decimal places.
This uses the format specifier language explained in the [documentation](http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax).
The default `toString()` format used in your original code is spelled out [here](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#toString%28double%29)."}
{"_id": 220, "title": "", "text": "```java double dexp = 12345678; System.out.printf(\"dexp: %f\\n\", dexp);
```"}
{"_id": 221, "title": "", "text": "### Format String Syntax
Every method which produces formatted output requires a *format string* and an *argument list*. The format string is a [`String`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html) which may contain fixed text and one or more embedded *format specifiers*. Consider the following example:
> Calendar c = ...; String s = String.format(\"Duke's Birthday: %1$tm %1$te,%1$tY\", c); >
This format string is the first argument to the
``` format ```
method. It contains three format specifiers \"
``` %1$tm ```
\", \"
``` %1$te ```
\", and \"
``` %1$tY ```
\" which indicate how the arguments should be processed and where they should be inserted in the text. The remaining portions of the format string are fixed text including
``` \"Dukes Birthday: \" ```
and any other spaces or punctuation. The argument list consists of all arguments passed to the method after the format string. In the above example, the argument list is of size one and consists of the
The optional *argument_index* is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by \"`1$`\", the second by \"`2$`\", etc.
The optional *flags* is a set of characters that modify the output format. The set of valid flags depends on the conversion.
The optional *width* is a non-negative decimal integer indicating the minimum number of characters to be written to the output.
The optional *precision* is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion.
The required *conversion* is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.
- The format specifiers for types which are used to represents dates and times have the following syntax:
> %[argument_index$][flags][width]conversion >
The optional *argument_index*, *flags* and *width* are defined as above.
The required *conversion* is a two character sequence. The first character is `'t'` or `'T'`. The second character indicates the format to be used. These characters are similar to but not completely identical to those defined by GNU `date` and POSIX `strftime(3c)`.
- The format specifiers which do not correspond to arguments have the following syntax:
> %[flags][width]conversion >
The optional *flags* and *width* is defined as above.
The required *conversion* is a character indicating content to be inserted in the output."}
{"_id": 222, "title": "", "text": "You can use any of the following options based on the requirements.
## [`Scanner`](http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html) class
```java import java.util.Scanner; //... Scanner scan = new Scanner(System.in); String s = scan.next(); int i = scan.nextInt();
```
---
## [`BufferedReader`](http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html) and [`InputStreamReader`](http://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html) classes
```java import java.io.BufferedReader; import java.io.InputStreamReader; //... BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int i = Integer.parseInt(s);
```
---
### [`DataInputStream`](http://docs.oracle.com/javase/8/docs/api/java/io/DataInputStream.html) class
```java import java.io.DataInputStream; //... DataInputStream dis = new DataInputStream(System.in); int i = dis.readInt();
```
The `readLine` method from the `DataInputStream` class has been *deprecated*. To get String value, you should use the previous solution with BufferedReader
---
### [`Console`](http://docs.oracle.com/javase/8/docs/api/java/io/Console.html) class
```java import java.io.Console; //... Console console = System.console(); String s = console.readLine(); int i = Integer.parseInt(console.readLine());
```
Apparently, this method does not work well in some IDEs."}
{"_id": 223, "title": "", "text": "```java import java.util.Scanner; //... Scanner scan = new Scanner(System.in); String s = scan.next(); int i = scan.nextInt();
```"}
{"_id": 224, "title": "", "text": "## Class Scanner
- [java.lang.Object](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html) - java.util.Scanner - **All Implemented Interfaces:**[Closeable](https://docs.oracle.com/javase/8/docs/api/java/io/Closeable.html), [AutoCloseable](https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html), [Iterator](https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html)<[String](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html)>A simple text scanner which can parse primitive types and strings using regular expressions.
---
``` public final classScanner extendsObject implementsIterator,Closeable ```
A `Scanner` breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
> Scanner sc = new Scanner(System.in); int i = sc.nextInt(); >
As another example, this code allows `long` types to be assigned from entries in a file `myNumbers`:
> Scanner sc = new Scanner(new File(\"myNumbers\")); while (sc.hasNextLong()) { long aLong = sc.nextLong(); } >
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
> String input = \"1 fish 2 fish red fish blue fish\"; Scanner s = new Scanner(input).useDelimiter(\"\\\\s*fish\\\\s*\"); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close(); >
prints the following output:
> 1 2 red blue >
The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:
> String input = \"1 fish 2 fish red fish blue fish\"; Scanner s = new Scanner(input); s.findInLine(\"(\\\\d+) fish (\\\\d+) fish (\\\\w+) fish (\\\\w+)\"); MatchResult result = s.match(); for (int i=1; i<=result.groupCount(); i++) System.out.println(result.group(i)); s.close(); >
The default whitespace delimiter used by a scanner is as recognized by [`Character`](https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html).[`isWhitespace`](https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#isWhitespace-char-). The [`reset()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#reset--) method will reset the value of the scanner's delimiter to the default whitespace delimiter regardless of whether it was previously changed.
A scanning operation may block waiting for input.
The [`next()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#next--) and [`hasNext()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#hasNext--) methods and their primitive-type companion methods (such as [`nextInt()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextInt--) and [`hasNextInt()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#hasNextInt--)) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
The [`findInLine(java.lang.String)`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#findInLine-java.lang.String-), [`findWithinHorizon(java.lang.String, int)`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#findWithinHorizon-java.lang.String-int-), and [`skip(java.util.regex.Pattern)`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#skip-java.util.regex.Pattern-) methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input.
When a scanner throws an [`InputMismatchException`](https://docs.oracle.com/javase/8/docs/api/java/util/InputMismatchException.html), the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern \"\\\\s+\" will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern \"\\\\s\" could return empty tokens since it only passes one space at a time.
A scanner can read text from any object which implements the [`Readable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Readable.html) interface. If an invocation of the underlying readable's [`Readable.read(java.nio.CharBuffer)`](https://docs.oracle.com/javase/8/docs/api/java/lang/Readable.html#read-java.nio.CharBuffer-) method throws an [`IOException`](https://docs.oracle.com/javase/8/docs/api/java/io/IOException.html) then the scanner assumes that the end of the input has been reached. The most recent IOException thrown by the underlying readable can be retrieved via the [`ioException()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#ioException--) method.
When a `Scanner` is closed, it will close its input source if the source implements the [`Closeable`](https://docs.oracle.com/javase/8/docs/api/java/io/Closeable.html) interface.
A `Scanner` is not safe for multithreaded use without external synchronization.
Unless otherwise mentioned, passing a `null` parameter into any method of a `Scanner` will cause a `NullPointerException` to be thrown.
A scanner will default to interpreting numbers as decimal unless a different radix has been set by using the [`useRadix(int)`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#useRadix-int-) method. The [`reset()`](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#reset--) method will reset the value of the scanner's radix to `10` regardless of whether it was previously changed."}
{"_id": 225, "title": "", "text": "Use:
```java public void listFilesForFolder(final File folder) { for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { listFilesForFolder(fileEntry); } else { System.out.println(fileEntry.getName()); } } }
final File folder = new File(\"/home/you/Desktop\"); listFilesForFolder(folder);
```
The [Files.walk](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-java.nio.file.FileVisitOption...-) API is available from Java 8.
The example uses the [try-with-resources](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) pattern recommended in the API guide. It ensures that no matter circumstances, the stream will be closed."}
{"_id": 226, "title": "", "text": "```java public void listFilesForFolder(final File folder) { for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { listFilesForFolder(fileEntry); } else { System.out.println(fileEntry.getName()); } } }
final File folder = new File(\"/home/you/Desktop\"); listFilesForFolder(folder);
```"}
{"_id": 227, "title": "", "text": "- walkReturn a `Stream` that is lazily populated with `Path` by walking the file tree rooted at a given starting file. The file tree is traversed *depth-first*, the elements in the stream are [`Path`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html) objects that are obtained as if by [`resolving`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html#resolve-java.nio.file.Path-) the relative path against `start`.In other words, it visits all levels of the file tree.
``` public staticStream walk(Path start, FileVisitOption... options) throwsIOException ```
This method works as if invoking it were equivalent to evaluating the expression:
> walk(start, Integer.MAX_VALUE, options) >
The returned stream encapsulates one or more [`DirectoryStream`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/DirectoryStream.html)s. If timely disposal of file system resources is required, the `try`-with-resources construct should be used to ensure that the stream's [`close`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/BaseStream.html#close--) method is invoked after the stream operations are completed. Operating on a closed stream will result in an [`IllegalStateException`](https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html).
**Parameters:**`start` - the starting file`options` - options to configure the traversal**Returns:**the [`Stream`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html) of [`Path`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html)**Throws:**[`SecurityException`](https://docs.oracle.com/javase/8/docs/api/java/lang/SecurityException.html) - If the security manager denies access to the starting file. In the case of the default provider, the [`checkRead`](https://docs.oracle.com/javase/8/docs/api/java/lang/SecurityManager.html#checkRead-java.lang.String-) method is invoked to check read access to the directory.[`IOException`](https://docs.oracle.com/javase/8/docs/api/java/io/IOException.html) - if an I/O error is thrown when accessing the starting file.**Since:**1.8**See Also:**[`walk(Path, int, FileVisitOption...)`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walk-java.nio.file.Path-int-java.nio.file.FileVisitOption...-)"}
{"_id": 228, "title": "", "text": "You can try using [System.arraycopy()](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy%28java.lang.Object,%20int,%20java.lang.Object,%20int,%20int%29)
```java int[] src = new int[]{1,2,3,4,5}; int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );
```
But, probably better to use clone() in most cases:
```java int[] src = ... int[] dest = src.clone(); ```"}
{"_id": 229, "title": "", "text": "```java int[] src = new int[]{1,2,3,4,5}; int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );
```"}
{"_id": 230, "title": "", "text": "- arraycopyCopies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components are copied from the source array referenced by `src` to the destination array referenced by `dest`. The number of components copied is equal to the `length` argument. The components at positions `srcPos` through `srcPos+length-1` in the source array are copied into positions `destPos` through `destPos+length-1`, respectively, of the destination array.
``` public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) ```
If the `src` and `dest` arguments refer to the same array object, then the copying is performed as if the components at positions `srcPos` through `srcPos+length-1` were first copied to a temporary array with `length` components and then the contents of the temporary array were copied into positions `destPos` through `destPos+length-1` of the destination array.
If `dest` is `null`, then a `NullPointerException` is thrown.
If `src` is `null`, then a `NullPointerException` is thrown and the destination array is not modified.
Otherwise, if any of the following is true, an `ArrayStoreException` is thrown and the destination is not modified:
- The `src` argument refers to an object that is not an array. - The `dest` argument refers to an object that is not an array. - The `src` argument and `dest` argument refer to arrays whose component types are different primitive types. - The `src` argument refers to an array with a primitive component type and the `dest` argument refers to an array with a reference component type. - The `src` argument refers to an array with a reference component type and the `dest` argument refers to an array with a primitive component type.
Otherwise, if any of the following is true, an `IndexOutOfBoundsException` is thrown and the destination is not modified:
- The `srcPos` argument is negative. - The `destPos` argument is negative. - The `length` argument is negative. - `srcPos+length` is greater than `src.length`, the length of the source array. - `destPos+length` is greater than `dest.length`, the length of the destination array.
Otherwise, if any actual component of the source array from position `srcPos` through `srcPos+length-1` cannot be converted to the component type of the destination array by assignment conversion, an `ArrayStoreException` is thrown. In this case, let ***k*** be the smallest nonnegative integer less than length such that `src[srcPos+`*k*`]` cannot be converted to the component type of the destination array; when the exception is thrown, source array components from positions `srcPos` through `srcPos+`*k*`-1` will already have been copied to destination array positions `destPos` through `destPos+`*k*`-1` and no other positions of the destination array will have been modified. (Because of the restrictions already itemized, this paragraph effectively applies only to the situation where both arrays have component types that are reference types.)
**Parameters:**`src` - the source array.`srcPos` - starting position in the source array.`dest` - the destination array.`destPos` - starting position in the destination data.`length` - the number of array elements to be copied.**Throws:**[`IndexOutOfBoundsException`](https://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html) - if copying would cause access of data outside array bounds.[`ArrayStoreException`](https://docs.oracle.com/javase/7/docs/api/java/lang/ArrayStoreException.html) - if an element in the `src` array could not be stored into the `dest` array because of a type mismatch.[`NullPointerException`](https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html) - if either `src` or `dest` is `null`."}
{"_id": 231, "title": "", "text": "Since Java 1.5, [`String.format()`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-) can be used to left/right pad a given string.
```java public static String padRight(String s, int n) { return String.format(\"%-\" + n + \"s\", s); }
public static String padLeft(String s, int n) { return String.format(\"%\" + n + \"s\", s); }
```"}
{"_id": 233, "title": "", "text": "- formatReturns a formatted string using the specified format string and arguments.
``` public staticString format(String format, Object... args) ```
The locale always used is the one returned by [`Locale.getDefault()`](https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#getDefault--).
**Parameters:**`format` - A [format string](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax)`args` - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by The Java™ Virtual Machine Specification. The behaviour on a `null` argument depends on the [conversion](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax).**Returns:**A formatted string**Throws:**[`IllegalFormatException`](https://docs.oracle.com/javase/8/docs/api/java/util/IllegalFormatException.html) - If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments, insufficient arguments given the format string, or other illegal conditions. For specification of all possible formatting errors, see the [Details](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#detail) section of the formatter class specification.**Since:**1.5**See Also:**[`Formatter`](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html)"}
{"_id": 234, "title": "", "text": "Neither of them. If you define it, it's not the default.
The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are `String`, `int` and `int`, and that the class itself is public:
And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.
See the [Java specifications](https://docs.oracle.com/javase/specs/), specifically: Section [8.8.9. Default Constructor](https://docs.oracle.com/javase/specs/jls/se22/html/jls-8.html#jls-8.8.9) of *Java Language Specification*.
> If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows: > > - The default constructor has the same access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access (§6.6). > - The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3). > - The default constructor has no `throws` clause.
### Clarification
Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because
- the question got the defaults wrong, and - the constructor has exactly the same effect whether they are included or not."}
{"_id": 235, "title": "", "text": "```java public Module() { super(); this.name = null; this.credits = 0; this.hours = 0; }
```"}
{"_id": 236, "title": "", "text": "If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:
- The default constructor has the same access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access ([§6.6](https://docs.oracle.com/javase/specs/jls/se22/html/jls-6.html#jls-6.6)). - The default constructor has no formal parameters, except in a non-`private` inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class ([§8.8.1](https://docs.oracle.com/javase/specs/jls/se22/html/jls-8.html#jls-8.8.1), [§15.9.2](https://docs.oracle.com/javase/specs/jls/se22/html/jls-15.html#jls-15.9.2), [§15.9.3](https://docs.oracle.com/javase/specs/jls/se22/html/jls-15.html#jls-15.9.3)). - The default constructor has no `throws` clause. - If the class being declared is the primordial class `Object`, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.
The form of the default constructor for an anonymous class is specified in [§15.9.5.1](https://docs.oracle.com/javase/specs/jls/se22/html/jls-15.html#jls-15.9.5.1)."}
{"_id": 237, "title": "", "text": "Java will always try to use the most specific applicable version of a method that's available (see [JLS §15.12.2](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5)).
`Object`, `char[]` and `Integer` can all take `null` as a valid value. Therefore all 3 version are applicable, so Java will have to find the most specific one.
Since `Object` is the super-type of `char[]`, the array version is more specific than the `Object`-version. So if only those two methods exist, the `char[]` version will be chosen.
When both the `char[]` and `Integer` versions are available, then **both** of them are more specific than `Object` but none is more specific than the other, so Java can't decide which one to call. In this case you'll have to explicitly mention which one you want to call by casting the argument to the appropriate type.
Note that in practice this problem occurs far more seldom than one might think. The reason for this is that it only happens when you're explicitly calling a method with `null` or with a variable of a rather un-specific type (such as `Object`).
On the contrary, the following invocation would be perfectly unambiguous:
```java char[] x = null; doSomething(x);
```
Although you're still passing the value `null`, Java knows exactly which method to call, since it will take the type of the variable into account."}
{"_id": 238, "title": "", "text": "```java char[] x = null; doSomething(x);
```"}
{"_id": 239, "title": "", "text": "**15.12.2.5. Choosing the Most Specific Method**
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the *most specific* method is chosen.
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
One fixed-arity member method named `m` is *more specific* than another member method of the same name and arity if all of the following conditions hold:
- The declared types of the parameters of the first member method are T1, ..., Tn. - The declared types of the parameters of the other method are U1, ..., Un. - If the second method is generic, then let R1 ... Rp (*p* ≥ 1) be its type parameters, let Bl be the declared bound of Rl (1 ≤ *l* ≤ *p*), let A1 ... Ap be the type arguments inferred ([§15.12.2.7](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.7)) for this invocation under the initial constraints Ti << Ui (1 ≤ *i* ≤ *n*), and let Si = Ui`[`R1=A1,...,Rp=Ap`]` (1 ≤ *i* ≤ *n*).
Otherwise, let Si = Ui (1 ≤ *i* ≤ *n*).
- For all *j* from 1 to *n*, Tj `<:` Sj. - If the second method is a generic method as described above, then Al `<:` Bl`[`R1=A1,...,Rp=Ap`]` (1 ≤ *l* ≤ *p*)."}
{"_id": 240, "title": "", "text": "`split(delimiter)` by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of `split(delimiter, limit)` with `limit` set to negative value like
`split(regex)` internally returns result of `split(regex, 0)` and in [documentation](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-int-) of this method you can find (emphasis mine)
> The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. > > > If the limit `n` is *greater than zero* then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. > > If `n` is **non-positive** then the pattern will be applied as many times as possible and the array can have any length. > > If `n` is **zero** then the pattern will be applied as many times as possible, the array can have any length, and **trailing empty strings will be discarded**. >
**Exception**:
It is worth mentioning that removing trailing empty string makes sense *only if such empty strings were created by the split mechanism*. So for `\"\".split(anything)` since we can't split `\"\"` farther we will get as result `[\"\"]` array.
It happens because split didn't happen here, so `\"\"` despite being empty and trailing represents *original* string, not empty string which was *created* by splitting process."}
{"_id": 241, "title": "", "text": "```java String[] split = data.split(\"\\\\|\", -1);
```"}
{"_id": 242, "title": "", "text": "The `limit` parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit *n* is greater than zero then the pattern will be applied at most *n* - 1 times, the array's length will be no greater than *n*, and the array's last entry will contain all input beyond the last matched delimiter. If *n* is non-positive then the pattern will be applied as many times as possible and the array can have any length. If *n* is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded."}
{"_id": 243, "title": "", "text": "From **JDK 7** you can use [`Files.readAllBytes(Path)`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllBytes(java.nio.file.Path)).
File file; // ...(file is initialised)... byte[] fileContent = Files.readAllBytes(file.toPath()); ```"}
{"_id": 245, "title": "", "text": "- readAllBytesReads all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.
```java public static byte[] readAllBytes(Path path) throwsIOException ```
Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.
**Parameters:**`path` - the path to the file**Returns:**a byte array containing the bytes read from the file**Throws:**[`IOException`](https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) - if an I/O error occurs reading from the stream[`OutOfMemoryError`](https://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html) - if an array of the required size cannot be allocated, for example the file is larger that `2GB[SecurityException](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityException.html)` - In the case of the default provider, and a security manager is installed, the [`checkRead`](https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkRead(java.lang.String)) method is invoked to check read access to the file."}
{"_id": 246, "title": "", "text": "*Edit*: as of Java 8, [lambda expressions](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) are a nice solution as [other](https://stackoverflow.com/a/19624032/21849) [answers](https://stackoverflow.com/a/25005082/21849) have pointed out. The answer below was written for Java 7 and earlier...
---
Take a look at the [command pattern](http://en.wikipedia.org/wiki/Command_pattern).
```java // NOTE: code not tested, but I believe this is valid java... public class CommandExample { public interface Command { public void execute(Object data); }
public class PrintCommand implements Command { public void execute(Object data) { System.out.println(data.toString()); } }
public static void callCommand(Command command, Object data) { command.execute(data); }
*Edit:* as [Pete Kirkham points out](https://stackoverflow.com/questions/2186931/java-pass-method-as-parameter/2186993#2186993), there's another way of doing this using a [Visitor](http://en.wikipedia.org/wiki/Visitor_pattern). The visitor approach is a little more involved - your nodes all need to be visitor-aware with an `acceptVisitor()` method - but if you need to traverse a more complex object graph then it's worth examining."}
{"_id": 247, "title": "", "text": "```java // NOTE: code not tested, but I believe this is valid java... public class CommandExample { public interface Command { public void execute(Object data); }
public class PrintCommand implements Command { public void execute(Object data) { System.out.println(data.toString()); } }
public static void callCommand(Command command, Object data) { command.execute(data); }
```"}
{"_id": 248, "title": "", "text": "One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data.
The previous section, [Anonymous Classes](https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html), shows you how to implement a base class without giving it a name. Although this is often more concise than a named class, for classes with only one method, even an anonymous class seems a bit excessive and cumbersome. Lambda expressions let you express instances of single-method classes more compactly."}
{"_id": 249, "title": "", "text": "Using [`java.io.File`](https://docs.oracle.com/javase/9/docs/api/java/io/File.html):
```java File f = new File(filePathString); if(f.exists() && !f.isDirectory()) { // do something } ```"}
{"_id": 250, "title": "", "text": "```java File f = new File(filePathString); if(f.exists() && !f.isDirectory()) { // do something } ```"}
{"_id": 251, "title": "", "text": "``` public classFile extendsObject implementsSerializable,Comparable ```
An abstract representation of file and directory pathnames.
User interfaces and operating systems use system-dependent *pathname strings* to name files and directories. This class presents an abstract, system-independent view of hierarchical pathnames. An *abstract pathname* has two components:
1. An optional system-dependent *prefix* string, such as a disk-drive specifier, `\"/\"` for the UNIX root directory, or `\"\\\\\\\"` for a Microsoft Windows UNC pathname, and 2. A sequence of zero or more string *names*.
The first name in an abstract pathname may be a directory name or, in the case of Microsoft Windows UNC pathnames, a hostname. Each subsequent name in an abstract pathname denotes a directory; the last name may denote either a directory or a file. The
*empty*
abstract pathname has no prefix and an empty name sequence.
The conversion of a pathname string to or from an abstract pathname is inherently system-dependent. When an abstract pathname is converted into a pathname string, each name is separated from the next by a single copy of the default *separator character*. The default name-separator character is defined by the system property `file.separator`, and is made available in the public static fields [`separator`](https://docs.oracle.com/javase/9/docs/api/java/io/File.html#separator) and [`separatorChar`](https://docs.oracle.com/javase/9/docs/api/java/io/File.html#separatorChar) of this class. When a pathname string is converted into an abstract pathname, the names within it may be separated by the default name-separator character or by any other name-separator character that is supported by the underlying system."}
{"_id": 252, "title": "", "text": "FileChannel.lock is probably what you want.
```java try ( FileInputStream in = new FileInputStream(file); java.nio.channels.FileLock lock = in.getChannel().lock(); Reader reader = new InputStreamReader(in, charset) ) { ... }
```
(Disclaimer: Code not compiled and certainly not tested.)
Note the section entitled \"platform dependencies\" in the [API doc for FileLock](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/channels/FileLock.html#pdep)."}
{"_id": 253, "title": "", "text": "```java try ( FileInputStream in = new FileInputStream(file); java.nio.channels.FileLock lock = in.getChannel().lock(); Reader reader = new InputStreamReader(in, charset) ) { ... }
This file-locking API is intended to map directly to the native locking facility of the underlying operating system. Thus the locks held on a file should be visible to all programs that have access to the file, regardless of the language in which those programs are written.
Whether or not a lock actually prevents another program from accessing the content of the locked region is system-dependent and therefore unspecified. The native file-locking facilities of some systems are merely *advisory*, meaning that programs must cooperatively observe a known locking protocol in order to guarantee data integrity. On other systems native file locks are *mandatory*, meaning that if one program locks a region of a file then other programs are actually prevented from accessing that region in a way that would violate the lock. On yet other systems, whether native file locks are advisory or mandatory is configurable on a per-file basis. To ensure consistent and correct behavior across platforms, it is strongly recommended that the locks provided by this API be used as if they were advisory locks.
On some systems, acquiring a mandatory lock on a region of a file prevents that region from being [`*mapped into memory*`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/channels/FileChannel.html#map(java.nio.channels.FileChannel.MapMode,long,long)), and vice versa. Programs that combine locking and mapping should be prepared for this combination to fail.
On some systems, closing a channel releases all locks held by the Java virtual machine on the underlying file regardless of whether the locks were acquired via that channel or via another channel open on the same file. It is strongly recommended that, within a program, a unique channel be used to acquire all locks on any given file.
Some network filesystems permit file locking to be used with memory-mapped files only when the locked regions are page-aligned and a whole multiple of the underlying hardware's page size. Some network filesystems do not implement file locks on regions that extend past a certain position, often 230 or 231. In general, great care should be taken when locking files that reside on network filesystems.
**Since:**1.4"}
{"_id": 255, "title": "", "text": "Indeed rather use [`ExecutorService`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html) instead of `Timer`, here's an [SSCCE](http://sscce.org/):
class Task implements Callable { @Override public String call() throws Exception { Thread.sleep(4000); // Just to demo a long running task of 4 seconds. return \"Ready!\"; } }
```
Play a bit with the `timeout` argument in [`Future#get()`](http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html#get%28long,%20java.util.concurrent.TimeUnit%29) method, e.g. increase it to 5 and you'll see that the thread finishes. You can intercept the timeout in the `catch (TimeoutException e)` block.
**Update:** to clarify a conceptual misunderstanding, the `sleep()` is **not** required. It is just used for SSCCE/demonstration purposes. Just do **your** long running task right there in place of `sleep()`. Inside your long running task, you should be checking if the thread is not [interrupted](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupted()) as follows:
```java while (!Thread.interrupted()) { // Do your long running task here. } ```"}
{"_id": 256, "title": "", "text": "```java package com.stackoverflow.q2275443;
class Task implements Callable { @Override public String call() throws Exception { Thread.sleep(4000); // Just to demo a long running task of 4 seconds. return \"Ready!\"; } }
```"}
{"_id": 257, "title": "", "text": "An [`Executor`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executor.html) that provides methods to manage termination and methods that can produce a [`Future`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html) for tracking progress of one or more asynchronous tasks.
An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The [`shutdown()`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#shutdown()) method will allow previously submitted tasks to execute before terminating, while the [`shutdownNow()`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#shutdownNow()) method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.
Method submit extends base method [`Executor.execute(java.lang.Runnable)`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executor.html#execute(java.lang.Runnable)) by creating and returning a [`Future`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html) that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class [`ExecutorCompletionService`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html) can be used to write customized variants of these methods.)
The [`Executors`](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html) class provides factory methods for the executor services provided in this package.
### Usage Examples
Here is a sketch of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured
``` class NetworkService implements Runnable { private final ServerSocket serverSocket; private final ExecutorService pool;
public NetworkService(int port, int poolSize) throws IOException { serverSocket = new ServerSocket(port); pool = Executors.newFixedThreadPool(poolSize); }
public void run() { // run the service try { for (;;) { pool.execute(new Handler(serverSocket.accept())); } } catch (IOException ex) { pool.shutdown(); } } }
class Handler implements Runnable { private final Socket socket; Handler(Socket socket) { this.socket = socket; } public void run() { // read and service request on socket } } ```"}
{"_id": 258, "title": "", "text": "You can use [`String unescapeJava(String)`](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringEscapeUtils.html#unescapeJava(java.lang.String)) method of [`StringEscapeUtils`](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringEscapeUtils.html) from [Apache Commons Lang](http://commons.apache.org/lang/).
Here's an example snippet:
```java String in = \"a\\\\tb\\\\n\\\\\\\"c\\\\\\\"\";
System.out.println(in); // a\\tb\\n\\\"c\\\"
String out = StringEscapeUtils.unescapeJava(in);
System.out.println(out); // a b // \"c\"
```
The utility class has methods to escapes and unescape strings for Java, Java Script, HTML, XML, and SQL. It also has overloads that writes directly to a [`java.io.Writer`](http://java.sun.com/javase/6/docs/api/java/io/Writer.html).
---
### Caveats
It looks like `StringEscapeUtils` handles Unicode escapes with one `u`, but not octal escapes, or Unicode escapes with extraneous `u`s.
> Octal escapes are provided for compatibility with C, but can express only Unicode values \\u0000 through \\u00FF, so Unicode escapes are usually preferred. >
If your string can contain octal escapes, you may want to convert them to Unicode escapes first, or use another approach.
The extraneous `u` is also documented as follows:
> The Java programming language specifies a standard way of transforming a program written in Unicode into ASCII that changes a program into a form that can be processed by ASCII-based tools. The transformation involves converting any Unicode escapes in the source text of the program to ASCII by adding an extra u-for example, \\uxxxx becomes \\uuxxxx-while simultaneously converting non-ASCII characters in the source text to Unicode escapes containing a single u each. > > > This transformed version is equally acceptable to a compiler for the Java programming language and represents the exact same program. The exact Unicode source can later be restored from this ASCII form by converting each escape sequence where multiple `u`'s are present to a sequence of Unicode characters with one fewer `u`, while simultaneously converting each escape sequence with a single `u` to the corresponding single Unicode character. >
If your string can contain Unicode escapes with extraneous `u`, then you may also need to preprocess this before using `StringEscapeUtils`.
Alternatively you can try to write your own Java string literal unescaper from scratch, making sure to follow the exact JLS specifications.
### References
- [JLS 3.3 Unicode Escapes](http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.3) - [JLS 3.10.6 Escape Sequences for Character and String Literals](http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.6)"}
{"_id": 259, "title": "", "text": "```java String in = \"a\\\\tb\\\\n\\\\\\\"c\\\\\\\"\";
System.out.println(in); // a\\tb\\n\\\"c\\\"
String out = StringEscapeUtils.unescapeJava(in);
System.out.println(out); // a b // \"c\"
```"}
{"_id": 260, "title": "", "text": "## Class StringEscapeUtils
as of 3.6, use commons-text [StringEscapeUtils](https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html) instead
``` @Deprecated public classStringEscapeUtils extendsObject ```
Escapes and unescapes `String`s for Java, Java Script, HTML and XML.
#ThreadSafe#
**Since:**2.0"}
{"_id": 261, "title": "", "text": "Convert it to [`String`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html) and use [`String#toCharArray()`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#toCharArray--) or [`String#split()`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-).
In case you're already on Java 8 and you happen to want to do some aggregate operations on it afterwards, consider using [`String#chars()`](http://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#chars--) to get an [`IntStream`](http://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html) out of it.
**Returns:**a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string."}
{"_id": 264, "title": "", "text": "Starting from Java-11, one can use the API [**`Collection.toArray(IntFunction generator)`**](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Collection.html#toArray(java.util.function.IntFunction)) to achieve the same as:
```java List list = List.of(\"x\",\"y\",\"z\"); String[] arrayBeforeJDK11 = list.toArray(new String[0]); String[] arrayAfterJDK11 = list.toArray(String[]::new); // simi ```"}
{"_id": 265, "title": "", "text": "```java List list = List.of(\"x\",\"y\",\"z\"); String[] arrayBeforeJDK11 = list.toArray(new String[0]); String[] arrayAfterJDK11 = list.toArray(String[]::new); // simi ```"}
{"_id": 266, "title": "", "text": "- toArrayReturns an array containing all of the elements in this collection, using the provided `generator` function to allocate the returned array.
If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.
**API Note:**This method acts as a bridge between array-based and collection-based APIs. It allows creation of an array of a particular runtime type. Use [`toArray()`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Collection.html#toArray()) to create an array whose runtime type is `Object[]`, or use [`toArray(T[])`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Collection.html#toArray(T%5B%5D)) to reuse an existing array. Suppose `x` is a collection known to contain only strings. The following code can be used to dump the collection into a newly allocated array of `String`:
`String[] y = x.toArray(String[]::new);` **Implementation Requirements:**The default implementation calls the generator function with zero and then passes the resulting array to [`toArray(T[])`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Collection.html#toArray(T%5B%5D)).**Type Parameters:**`T` - the component type of the array to contain the collection**Parameters:**`generator` - a function which produces a new array of the desired type and the provided length**Returns:**an array containing all of the elements in this collection**Throws:**[`ArrayStoreException`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/ArrayStoreException.html) - if the runtime type of any element in this collection is not assignable to the [runtime component type](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/Class.html#getComponentType()) of the generated array[`NullPointerException`](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/NullPointerException.html) - if the generator function is null**Since:**11"}
{"_id": 267, "title": "", "text": "The obvious answer, of course, is not to do the unchecked cast.
If it's absolutely necessary, then at least try to limit the scope of the `@SuppressWarnings` annotation. According to its [Javadocs](http://java.sun.com/javase/6/docs/api/java/lang/SuppressWarnings.html), it can go on local variables; this way, it doesn't even affect the entire method.
There is no way to determine whether the `Map` really should have the generic parameters ``. You must know beforehand what the parameters should be (or you'll find out when you get a `ClassCastException`). This is why the code generates a warning, because the compiler can't possibly know whether is safe."}
{"_id": 268, "title": "", "text": "```java @SuppressWarnings(\"unchecked\") Map myMap = (Map) deserializeMap();
```"}
{"_id": 269, "title": "", "text": "## Annotation Type SuppressWarnings
---
[`@Target](https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/Target.html)([value](https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/Target.html#value())={[TYPE](https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/ElementType.html#TYPE),[FIELD](https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/ElementType.html#FIELD),[METHOD](https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/ElementType.html#METHOD),[PARAMETER](https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/ElementType.html#PARAMETER),[CONSTRUCTOR](https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/ElementType.html#CONSTRUCTOR),[LOCAL_VARIABLE](https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/ElementType.html#LOCAL_VARIABLE)}) [@Retention](https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/Retention.html)([value](https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/Retention.html#value())=[SOURCE](https://docs.oracle.com/javase/6/docs/api/java/lang/annotation/RetentionPolicy.html#SOURCE)) public @interface **SuppressWarnings**`
Indicates that the named compiler warnings should be suppressed in the annotated element (and in all program elements contained in the annotated element). Note that the set of warnings suppressed in a given element is a superset of the warnings suppressed in all containing elements. For example, if you annotate a class to suppress one warning and annotate a method to suppress another, both warnings will be suppressed in the method.
As a matter of style, programmers should always use this annotation on the most deeply nested element where it is effective. If you want to suppress a warning in a particular method, you should annotate that method rather than its class.
**Since:**1.5"}
{"_id": 270, "title": "", "text": "What about [isEmpty()](http://download.oracle.com/javase/6/docs/api/java/lang/String.html#isEmpty()) ?
```java if(str != null && !str.isEmpty())
```
Be sure to use the parts of `&&` in this order, because java will not proceed to evaluate the second part if the first part of `&&` fails, thus ensuring you will not get a null pointer exception from `str.isEmpty()` if `str` is null.
Beware, it's only available since Java SE 1.6. You have to check `str.length() == 0` on previous versions.
---
To ignore whitespace as well:
```java if(str != null && !str.trim().isEmpty())
```
(since Java 11 `str.trim().isEmpty()` can be reduced to `str.isBlank()` which will also test for other Unicode white spaces)
Wrapped in a handy function:
```java public static boolean empty( final String s ) { // Null-safe, short-circuit evaluation. return s == null || s.trim().isEmpty(); }
Returns true if, and only if, [`length()`](https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#length()) is 0. **Returns:**true if [`length()`](https://docs.oracle.com/javase/6/docs/api/java/lang/String.html#length()) is 0, otherwise false**Since:**1.6"}
{"_id": 273, "title": "", "text": "Since [Java 1.5, yes](http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)):
```java Pattern.quote(\"$5\"); ```"}
{"_id": 274, "title": "", "text": "```java Pattern.quote(\"$5\"); ```"}
{"_id": 275, "title": "", "text": "- quoteReturns a literal pattern `String` for the specified `String`.Metacharacters or escape sequences in the input sequence will be given no special meaning.
``` public staticString quote(String s) ```
This method produces a `String` that can be used to create a `Pattern` that would match the string `s` as if it were a literal pattern.
**Parameters:**`s` - The string to be literalized**Returns:**A literal string replacement**Since:**1.5"}
{"_id": 276, "title": "", "text": "Yes.
However, I'm being pedantic here. *Scope* is a language concept that determines the validity of names. Whether an object can be garbage collected (and therefore finalized) depends on whether it is *reachable*.
The [answer from ajb](https://stackoverflow.com/a/24376863/1441122) almost had it (+1) by citing a significant passage from the JLS. However I don't think it's directly applicable to the situation. JLS [§12.6.1](http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.6.1) also says:
> A reachable object is any object that can be accessed in any potential continuing computation from any live thread. >
Now consider this applied to the following code:
```java class A { @Override protected void finalize() { System.out.println(this + \" was finalized!\"); }
public static void main(String[] args) { A a = new A(); System.out.println(\"Created \" + a); for (int i = 0; i < 1_000_000_000; i++) { if (i % 1_000_000 == 0) System.gc(); } // System.out.println(a + \" was still alive.\"); } }
```
On JDK 8 GA, this will finalize `a` every single time. If you uncomment the `println` at the end, `a` will never be finalized.
With the `println` commented out, one can see how the reachability rule applies. When the code reaches the loop, there is no possible way that the thread can have any access to `a`. Thus it is unreachable and is therefore subject to finalization and garbage collection.
Note that the name `a` is still *in scope* because one can use `a` anywhere within the enclosing block -- in this case the `main` method body -- from its declaration to the end of the block. The exact scope rules are covered in JLS [§6.3](http://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.3). But really, as you can see, scope has nothing to do with reachability or garbage collection.
To prevent the object from being garbage collected, you can store a reference to it in a static field, or if you don't want to do that, you can keep it reachable by using it later on in the same method after the time-consuming loop. It should be sufficient to call an innocuous method like `toString` on it."}
{"_id": 277, "title": "", "text": "```java class A { @Override protected void finalize() { System.out.println(this + \" was finalized!\"); }
public static void main(String[] args) { A a = new A(); System.out.println(\"Created \" + a); for (int i = 0; i < 1_000_000_000; i++) { if (i % 1_000_000 == 0) System.gc(); } // System.out.println(a + \" was still alive.\"); } }
Every object can be characterized by two attributes: it may be *reachable*, *finalizer-reachable*, or *unreachable*, and it may also be *unfinalized*, *finalizable*, or *finalized*.
A *reachable* object is any object that can be accessed in any potential continuing computation from any live thread.
A *finalizer-reachable* object can be reached from some finalizable object through some chain of references, but not from any live thread.
An *unreachable* object cannot be reached by either means.
An *unfinalized* object has never had its finalizer automatically invoked.
A *finalized* object has had its finalizer automatically invoked.
A *finalizable* object has never had its finalizer automatically invoked, but the Java Virtual Machine may eventually automatically invoke its finalizer."}
{"_id": 279, "title": "", "text": "To be able to call [notify()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#notify()) you need to synchronize on the same object.
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the `wait` methods. The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object. This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways: • By executing a synchronized instance method of that object. • By executing the body of a `synchronized` statement that synchronizes on the object. • For objects of type `Class,` by executing a synchronized static method of that class. Only one thread at a time can own an object's monitor. **Throws:**[`IllegalMonitorStateException`](https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/IllegalMonitorStateException.html) - if the current thread is not the owner of this object's monitor.**See Also:**[`notifyAll()`](https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#notifyAll()), [`wait()`](https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#wait())"}
{"_id": 282, "title": "", "text": "As shown by @Maglob, the basic approach is to test the conversion from string to date using [SimpleDateFormat.parse](http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html). That will catch invalid day/month combinations like 2008-02-31.
However, in practice that is rarely enough since SimpleDateFormat.parse is exceedingly liberal. There are two behaviours you might be concerned with:
**Invalid characters in the date string** Surprisingly, 2008-02-2x will \"pass\" as a valid date with locale format = \"yyyy-MM-dd\" for example. Even when isLenient==false.
**Years: 2, 3 or 4 digits?** You may also want to enforce 4-digit years rather than allowing the default SimpleDateFormat behaviour (which will interpret \"12-02-31\" differently depending on whether your format was \"yyyy-MM-dd\" or \"yy-MM-dd\")
## A Strict Solution with the Standard Library
So a complete string to date test could look like this: a combination of regex match, and then a forced date conversion. The trick with the regex is to make it locale-friendly.
```java Date parseDate(String maybeDate, String format, boolean lenient) { Date date = null;
// test date string matches format structure using regex // - weed out illegal characters and enforce 4-digit year // - create the regex based on the local format string String reFormat = Pattern.compile(\"d+|M+\").matcher(Matcher.quoteReplacement(format)).replaceAll(\"\\\\\\\\d{1,2}\"); reFormat = Pattern.compile(\"y+\").matcher(reFormat).replaceAll(\"\\\\\\\\d{4}\"); if ( Pattern.compile(reFormat).matcher(maybeDate).matches() ) {
// date string matches format structure, // - now test it can be converted to a valid date SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(); sdf.applyPattern(format); sdf.setLenient(lenient); try { date = sdf.parse(maybeDate); } catch (ParseException e) { } } return date; }
// used like this: Date date = parseDate( \"21/5/2009\", \"d/M/yyyy\", false);
```
Note that the regex assumes the format string contains only day, month, year, and separator characters. Aside from that, format can be in any locale format: \"d/MM/yy\", \"yyyy-MM-dd\", and so on. The format string for the current locale could be obtained like this:
```java Locale locale = Locale.getDefault(); SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale ); String format = sdf.toPattern(); ```"}
{"_id": 283, "title": "", "text": "```java Date parseDate(String maybeDate, String format, boolean lenient) { Date date = null;
// test date string matches format structure using regex // - weed out illegal characters and enforce 4-digit year // - create the regex based on the local format string String reFormat = Pattern.compile(\"d+|M+\").matcher(Matcher.quoteReplacement(format)).replaceAll(\"\\\\\\\\d{1,2}\"); reFormat = Pattern.compile(\"y+\").matcher(reFormat).replaceAll(\"\\\\\\\\d{4}\"); if ( Pattern.compile(reFormat).matcher(maybeDate).matches() ) {
// date string matches format structure, // - now test it can be converted to a valid date SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(); sdf.applyPattern(format); sdf.setLenient(lenient); try { date = sdf.parse(maybeDate); } catch (ParseException e) { } } return date; }
// used like this: Date date = parseDate( \"21/5/2009\", \"d/M/yyyy\", false);
```"}
{"_id": 284, "title": "", "text": "`public class **SimpleDateFormat**extends [DateFormat](https://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html)`
`SimpleDateFormat` is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization.
`SimpleDateFormat` allows you to start by choosing any user-defined patterns for date-time formatting. However, you are encouraged to create a date-time formatter with either `getTimeInstance`, `getDateInstance`, or `getDateTimeInstance` in `DateFormat`. Each of these class methods can return a date/time formatter initialized with a default format pattern. You may modify the format pattern using the `applyPattern` methods as desired. For more information on using these methods, see [`DateFormat`](https://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html).
### Date and Time Patterns
Date and time formats are specified by *date and time pattern* strings. Within date and time pattern strings, unquoted letters from `'A'` to `'Z'` and from `'a'` to `'z'` are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (`'`) to avoid interpretation. `\"''\"` represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing."}
{"_id": 285, "title": "", "text": "I believe you also have to use `.detach()`. I had to convert my Tensor to a numpy array on Colab which uses CUDA and GPU. I did it like the following:
```python # this is just my embedding matrix which is a Torch tensor object embedding = learn.model.u_weight
embedding_list = list(range(0, 64382))
input = torch.cuda.LongTensor(embedding_list) tensor_array = embedding(input) # the output of the line below is a numpy array tensor_array.cpu().detach().numpy() ```"}
{"_id": 286, "title": "", "text": "```python # this is just my embedding matrix which is a Torch tensor object embedding = learn.model.u_weight
embedding_list = list(range(0, 64382))
input = torch.cuda.LongTensor(embedding_list) tensor_array = embedding(input) # the output of the line below is a numpy array tensor_array.cpu().detach().numpy() ```"}
{"_id": 287, "title": "", "text": "# **torch.Tensor.detach**
**Tensor.detach()Returns a new Tensor, detached from the current graph. The result will never require gradient. This method also affects forward mode AD gradients and the result will never have forward mode AD gradients. NOTE Returned Tensor shares the same storage with the original one. In-place modifications on either of them will be seen, and may trigger errors in correctness checks.**"}
{"_id": 288, "title": "", "text": "`view()` reshapes the tensor without copying memory, similar to numpy's [`reshape()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html).
Given a tensor `a` with 16 elements:
```python import torch a = torch.range(1, 16)
```
To reshape this tensor to make it a `4 x 4` tensor, use:
```python a = a.view(4, 4)
```
Now `a` will be a `4 x 4` tensor. *Note that after the reshape the total number of elements need to remain the same. Reshaping the tensor `a` to a `3 x 5` tensor would not be appropriate.*"}
{"_id": 289, "title": "", "text": "```python import torch a = torch.range(1, 16) a = a.view(4, 4) ```"}
{"_id": 290, "title": "", "text": "# **torch.Tensor.view**
**Tensor.view(**shape*) → [Tensor](https://pytorch.org/docs/stable/tensors.html#torch.Tensor)Returns a new tensor with the same data as the `self` tensor but of a different [`shape`](https://pytorch.org/docs/stable/generated/torch.Tensor.shape.html#torch.Tensor.shape). The returned tensor shares the same data and must have the same number of elements, but may have a different size. For a tensor to be viewed, the new view size must be compatible with its original size and stride, i.e., each new view dimension must either be a subspace of an original dimension, or only span across original dimensions 𝑑,𝑑+1,…,𝑑+𝑘*d*,*d*+1,…,*d*+*k* that satisfy the following contiguity-like condition that ∀𝑖=𝑑,…,𝑑+𝑘−1∀*i*=*d*,…,*d*+*k*−1,stride[𝑖]=stride[𝑖+1]×size[𝑖+1]stride[*i*]=stride[*i*+1]×size[*i*+1] Otherwise, it will not be possible to view `self` tensor as [`shape`](https://pytorch.org/docs/stable/generated/torch.Tensor.shape.html#torch.Tensor.shape) without copying it (e.g., via [`contiguous()`](https://pytorch.org/docs/stable/generated/torch.Tensor.contiguous.html#torch.Tensor.contiguous)). When it is unclear whether a [`view()`](https://pytorch.org/docs/stable/generated/torch.Tensor.view.html#torch.Tensor.view) can be performed, it is advisable to use [`reshape()`](https://pytorch.org/docs/stable/generated/torch.reshape.html#torch.reshape), which returns a view if the shapes are compatible, and copies (equivalent to calling [`contiguous()`](https://pytorch.org/docs/stable/generated/torch.Tensor.contiguous.html#torch.Tensor.contiguous)) otherwise.Parametersshape (*torch.Size or [int](https://docs.python.org/3/library/functions.html#int)...*) – the desired size Example:
`>>> x = torch.randn(4, 4)>>> x.size()torch.Size([4, 4]) >>> y = x.view(16)>>> y.size()torch.Size([16]) >>> z = x.view(-1, 8) *# the size -1 is inferred from other dimensions*>>> z.size()torch.Size([2, 8])
>>> a = torch.randn(1, 2, 3, 4)>>> a.size()torch.Size([1, 2, 3, 4]) >>> b = a.transpose(1, 2) *# Swaps 2nd and 3rd dimension*>>> b.size()torch.Size([1, 3, 2, 4]) >>> c = a.view(1, 3, 2, 4) *# Does not change tensor layout in memory*>>> c.size()torch.Size([1, 3, 2, 4]) >>> torch.equal(b, c)False`**"}
{"_id": 291, "title": "", "text": "Although
```python import torch torch.cuda.empty_cache()
```
provides a good alternative for clearing the occupied cuda memory and we can also manually clear the not in use variables by using,
```python import gc del variables gc.collect()
```
But still after using these commands, the error might appear again because pytorch doesn't actually clears the memory instead clears the reference to the memory occupied by the variables. So reducing the batch_size after restarting the kernel and finding the optimum batch_size is the best possible option (but sometimes not a very feasible one).
Another way to get a deeper insight into the alloaction of memory in gpu is to use:
wherein, both the arguments are optional. This gives a readable summary of memory allocation and allows you to figure the reason of CUDA running out of memory and restart the kernel to avoid the error from happening again (Just like I did in my case).
Passing the data iteratively might help but changing the size of layers of your network or breaking them down would also prove effective (as sometimes the model also occupies a significant memory for example, while doing transfer learning)."}
{"_id": 292, "title": "", "text": "```python import torch torch.cuda.empty_cache()
**torch.cuda.empty_cache()[[SOURCE]](https://pytorch.org/docs/stable/_modules/torch/cuda/memory.html#empty_cache)Release all unoccupied cached memory currently held by the caching allocator so that those can be used in other GPU application and visible in nvidia-smi. NOTE [`empty_cache()`](https://pytorch.org/docs/stable/generated/torch.cuda.empty_cache.html#torch.cuda.empty_cache) doesn’t increase the amount of GPU memory available for PyTorch. However, it may help reduce fragmentation of GPU memory in certain cases. See [Memory management](https://pytorch.org/docs/stable/notes/cuda.html#cuda-memory-management) for more details about GPU memory management.**"}
{"_id": 294, "title": "", "text": "`model.eval()` is a kind of switch for some specific layers/parts of the model that behave differently during training and inference (evaluating) time. For example, Dropouts Layers, BatchNorm Layers etc. You need to turn them off during model evaluation, and `.eval()` will do it for you. In addition, the common practice for evaluating/validation is using `torch.no_grad()` in pair with `model.eval()` to turn off gradients computation:
```python # evaluate model: model.eval()
with torch.no_grad(): ... out_data = model(data) ...
```
BUT, don't forget to turn back to `training` mode after eval step:
**Set the module in evaluation mode. This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g. [`Dropout`](https://pytorch.org/docs/stable/generated/torch.nn.Dropout.html#torch.nn.Dropout), `BatchNorm`, etc. This is equivalent with [`self.train(False)`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.train). See [Locally disabling gradient computation](https://pytorch.org/docs/stable/notes/autograd.html#locally-disable-grad-doc) for a comparison between .eval() and several similar mechanisms that may be confused with it.ReturnsselfReturn type[Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module)**"}
{"_id": 297, "title": "", "text": "I'm referring to the question in the title as you haven't really specified anything else in the text, so just converting the DataFrame into a PyTorch tensor.
Without information about your data, I'm just taking float values as example targets here.
**Convert Pandas dataframe to PyTorch tensor?**
```python import pandas as pd import torch import random
# creating dummy targets (float values) targets_data = [random.random() for i in range(10)]
I hope this helps, if you have any further questions - just ask. :)"}
{"_id": 298, "title": "", "text": " ```python import pandas as pd import torch import random
# creating dummy targets (float values) targets_data = [random.random() for i in range(10)]
**torch.tensor(*data*, ***, *dtype=None*, *device=None*, *requires_grad=False*, *pin_memory=False*) → [Tensor](https://pytorch.org/docs/master/tensors.html#torch.Tensor)Constructs a tensor with no autograd history (also known as a “leaf tensor”, see [Autograd mechanics](https://pytorch.org/docs/master/notes/autograd.html)) by copying `data`. WARNING When working with tensors prefer using [`torch.Tensor.clone()`](https://pytorch.org/docs/master/generated/torch.Tensor.clone.html#torch.Tensor.clone), [`torch.Tensor.detach()`](https://pytorch.org/docs/master/generated/torch.Tensor.detach.html#torch.Tensor.detach), and [`torch.Tensor.requires_grad_()`](https://pytorch.org/docs/master/generated/torch.Tensor.requires_grad_.html#torch.Tensor.requires_grad_) for readability. Letting t be a tensor, `torch.tensor(t)` is equivalent to `t.clone().detach()`, and `torch.tensor(t, requires_grad=True)` is equivalent to `t.clone().detach().requires_grad_(True)`. SEE ALSO [`torch.as_tensor()`](https://pytorch.org/docs/master/generated/torch.as_tensor.html#torch.as_tensor) preserves autograd history and avoids copies where possible. [`torch.from_numpy()`](https://pytorch.org/docs/master/generated/torch.from_numpy.html#torch.from_numpy) creates a tensor that shares storage with a NumPy array.Parameters:data (*array_like*) – Initial data for the tensor. Can be a list, tuple, NumPy `ndarray`, scalar, and other types.Keyword Arguments: • dtype ([`torch.dtype`](https://pytorch.org/docs/master/tensor_attributes.html#torch.dtype), optional) – the desired data type of returned tensor. Default: if `None`, infers data type from `data`. • device ([`torch.device`](https://pytorch.org/docs/master/tensor_attributes.html#torch.device), optional) – the device of the constructed tensor. If None and data is a tensor then the device of data is used. If None and data is not a tensor then the result tensor is constructed on the CPU. • requires_grad ([*bool](https://docs.python.org/3/library/functions.html#bool), optional*) – If autograd should record operations on the returned tensor. Default: `False`. • pin_memory ([*bool](https://docs.python.org/3/library/functions.html#bool), optional*) – If set, returned tensor would be allocated in the pinned memory. Works only for CPU tensors. Default: `False`. Example:
>>> torch.tensor([0, 1]) *# Type inference on data*tensor([ 0, 1])
>>> torch.tensor([[0.11111, 0.222222, 0.3333333]],... dtype=torch.float64,... device=torch.device('cuda:0')) *# creates a double tensor on a CUDA device*tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0')
>>> torch.tensor(3.14159) *# Create a zero-dimensional (scalar) tensor*tensor(3.1416)
```markdown # How to access environment variables in Ruby?
To access environment variables in Ruby, you can use the `ENV` object.
```ruby # Example puts ENV['HOME'] # Outputs the home directory ```
More details can be found in the [Ruby documentation](https://ruby-doc.org/core-2.5.0/ENV.html). ```"}
{"_id": 1, "title": "", "text": "```javascript // Accessing environment variables in Node.js console.log(process.env.MY_VARIABLE); ```"}
{"_id": 2, "title": "", "text": "# Introduction to Environment Variables
Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer. These variables are part of the environment in which a process runs. They are used by the operating system to configure system behavior and the behavior of applications. Examples include `PATH`, `HOME`, `USER`, and many others. [Learn more on Wikipedia](https://en.wikipedia.org/wiki/Environment_variable)."}
{"_id": 3, "title": "", "text": "## How to Read a File in Python?
I'm trying to read the contents of a file in Python. What is the best way to do this?
### Answer 1
You can use the `open()` function to read a file in Python. Here is an example:
```python with open('example.txt', 'r') as file: contents = file.read() print(contents) ```
This code will open the file `example.txt` for reading, read its contents, and print them to the console."}
{"_id": 4, "title": "", "text": "```java import java.io.File;
public class CreateDirectory { public static void main(String[] args) { File dirs = new File(\"/path/to/parent/dirs\"); boolean result = dirs.mkdirs(); if(result) { System.out.println(\"Directories created successfully\"); } else { System.out.println(\"Failed to create directories\"); } } } ```"}
{"_id": 5, "title": "", "text": "## Creating and Navigating Directories in Java
In Java, you can use the `Files` class to create directories. For example:
public class CreateDirectory { public static void main(String[] args) { try { Files.createDirectories(Paths.get(\"/path/to/directory\")); } catch (IOException e) { e.printStackTrace(); } } } ```
This code creates a directory and any missing parent directories specified in the path."}
{"_id": 6, "title": "", "text": "```markdown ## What is the difference between private, protected, and public class members in Python?
I'm trying to understand the different access modifiers in Python. Could someone explain private, protected, and public class members?
### Answer: In Python, there isn't strict enforcement of private, protected, and public class members like in some other languages (e.g., Java or C++). However, there's a naming convention that indicates how these members should be accessed:
- **Public members**: These are accessible anywhere. - **Protected members**: Indicated by a single underscore `_`, suggesting they're intended for internal use only and shouldn't be accessed from outside the class. - **Private members**: Indicated by a double underscore `__`, making name mangling to prevent access from outside the class. ```"}
{"_id": 7, "title": "", "text": "```javascript class Example { static staticMethod() { console.log('This is a static method.'); }
This section covers the built-in functions provided by Python. Built-in functions are always available for use. For a complete list, refer to the [official documentation](https://docs.python.org/3/library/functions.html).
## Commonly Used Functions
- **abs()**: Return the absolute value of a number. - **all()**: Return True if all elements of the iterable are true. - **any()**: Return True if any element of the iterable is true. - **ascii()**: Return a string containing a printable representation of an object. ``` "}
{"_id": 9, "title": "", "text": "### Title: How to filter rows in a Pandas DataFrame
**Question:**
I'm trying to filter rows in a Pandas DataFrame based on certain conditions. What is the best way to achieve this?
**Answer:**
You can use the `loc` or `iloc` methods to filter rows. For example:
# Filter rows where column A is greater than 20 filtered_df = df.loc[df['A'] > 20] print(filtered_df) ``` This will result in:
``` A B 2 30 70 3 40 80 ``` You can also chain multiple conditions using `&` (and) and `|` (or). "}
{"_id": 10, "title": "", "text": "```javascript const data = [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }]; data.forEach(row => { console.log(`${row.name} is ${row.age} years old`); }); ```"}
{"_id": 11, "title": "", "text": "# Reading Data into a Pandas DataFrame
To begin working with data in a Pandas DataFrame, you first need to read the data into the DataFrame format. This can typically be done using the `read_csv` function for CSV files or `read_excel` for Excel files. Here is an example of how you can read a CSV file into a Pandas DataFrame:
```python import pandas as pd
df = pd.read_csv('data.csv') ```
For more information, please refer to the [Pandas official documentation](https://pandas.pydata.org/pandas-docs/stable/). "}
{"_id": 12, "title": "", "text": "```markdown ### How to use variables in Python functions?
In Python, you can declare variables inside a function to limit their scope to that function. Here's an example of a local variable in a function:
print(local_variable) # This will raise an error as local_variable is not defined outside the function ``` ```"}
{"_id": 13, "title": "", "text": "```java public class GlobalVarExample { static int globalVar = 10;
public static void main(String[] args) { modifyGlobalVar(); System.out.println(globalVar); }
In Python, variables are used to store data that can be manipulated and referenced. They can hold values such as numbers, strings, lists, dictionaries, and more. Variables in Python are dynamically typed, meaning that their data type is inferred at runtime.
Example: ```python x = 10 y = 'Hello, World!' ``` For more detailed information, you can refer to the [official Python documentation on variables](https://docs.python.org/3/tutorial/introduction.html#numbers-strings-and-variables)."}
{"_id": 15, "title": "", "text": "```markdown ### How to Convert List to String in Python 3?
I'm trying to convert a list of integers to a single string in Python 3. What would be the best approach to achieve this?
#### Example: ```python my_list = [1, 2, 3, 4, 5] result = ''.join(map(str, my_list)) print(result) # Output: '12345' ``` Any help would be appreciated! ``` "}
{"_id": 16, "title": "", "text": "```javascript let buffer = new Buffer('Hello World'); let str = buffer.toString('utf-8'); console.log(str); ```"}
{"_id": 17, "title": "", "text": "# Understanding Bytes and Strings in Python 3
In Python 3, strings are sequences of Unicode characters. On the other hand, bytes are sequences of bytes (8-bit values). It is important to differentiate between the two as they serve different purposes in data handling and manipulation.
Refer to the [official Python documentation](https://docs.python.org/3) for more details on the differences between bytes and strings. "}
{"_id": 18, "title": "", "text": "# How to get the current time in Java
You can use the `java.time.LocalTime` class to get the current time in Java. Here's a simple example:
```java import java.time.LocalTime;
public class CurrentTime { public static void main(String[] args) { LocalTime currentTime = LocalTime.now(); System.out.println(\"Current time: \" + currentTime); } } ```
This will print the current time in hours, minutes, and seconds."}
{"_id": 19, "title": "", "text": "```javascript let currentTime = new Date().toLocaleTimeString(); console.log(currentTime); ```"}
{"_id": 20, "title": "", "text": "# String Methods in Python
Python provides a range of string methods which are useful for various text processing tasks. For instance, `str.lower()` converts a string to lowercase, whereas `str.upper()` converts a string to uppercase. Another useful method is `str.split(separator)` which splits a string into a list based on a given separator. These methods make string manipulation extremely easy and intuitive in Python."}
{"_id": 21, "title": "", "text": "# Handling Multiple Exceptions in Python
Is it possible to catch multiple exceptions in Python in a single try block? I've been trying to handle different exception types differently but I don't want to repeat the same try-except structure. Any suggestions?"}
{"_id": 22, "title": "", "text": "```java try { // some code that may throw exceptions } catch (IOException | SQLException ex) { // handle exceptions } ```"}
{"_id": 23, "title": "", "text": "# Exception Handling in Python
In Python, exceptions are errors that occur during the execution of a program. They disrupt the normal flow of the program's instructions. Exceptions need to be caught and handled to prevent the program from crashing.
To handle exceptions, Python provides the `try` and `except` blocks. The `try` block contains the code that may raise an exception, while the `except` block contains the code that handles the exception. If no exception occurs, the code inside the `except` block is not executed.
```python try: # code that may raise an exception except ExceptionType: # handle the exception ```"}
{"_id": 24, "title": "", "text": "```markdown ### How to copy a list in Python?
I need to create a duplicate of a list in Python. What is the most efficient way to accomplish this?
**Answer:** You can use the `copy` module or list slicing to duplicate a list.
# Using list slicing duplicated_list = original_list[:] ``` ```"}
{"_id": 25, "title": "", "text": "```javascript // Using JavaScript to copy a file const fs = require('fs');
function copyFile(source, destination) { fs.copyFile(source, destination, (err) => { if (err) throw err; console.log('File was copied to destination'); }); }
copyFile('source.txt', 'destination.txt'); ```"}
{"_id": 26, "title": "", "text": "```markdown # Introduction to File Handling in Python
File handling is an important concept in programming. Python provides several functions to create, read, update, and delete files. File handling concept is mainly used in saving information on system memory or external memory, like text files or binary files.
### Opening a File in Python To open a file, you can use the `open()` function. It requires a file name and a mode parameter to specify the actions you want to perform on the file.
```python file = open('example.txt', 'r') ``` In this example, we open a file named 'example.txt' in read mode. ```"}
{"_id": 27, "title": "", "text": "## How to split a string in Python?
I'm trying to split a string into a list in Python. For example, I want to split the string 'Hello, World, Python' by the comma character. How can I achieve this?
```python s = 'Hello, World, Python' list_of_words = s.split(', ') print(list_of_words) # Output: ['Hello', 'World', 'Python'] ```"}
{"_id": 28, "title": "", "text": "```java public class Main { public static void main(String[] args) { String text = \"Hello, World!\"; if (text.contains(\"World\")) { System.out.println(\"Text contains 'World'\"); } } } ```"}
{"_id": 29, "title": "", "text": "# Overview of Strings in Java
In Java, you can check if a string contains a specific substring by using the `contains()` method of the `String` class.
This method returns `true` if and only if this string contains the specified sequence of char values."}
{"_id": 30, "title": "", "text": "## How to Delete a File in JavaScript?
You can use the `fs` module in Node.js to delete a file. Here is an example:
Make sure you have the `path/to/file` set to the correct file path you want to delete."}
{"_id": 31, "title": "", "text": "```java import java.io.File;
public class DeleteFile { public static void main(String[] args) { File myFile = new File(\"filename.txt\"); if (myFile.delete()) { System.out.println(\"Deleted the file: \" + myFile.getName()); } else { System.out.println(\"Failed to delete the file.\"); } } } ```"}
{"_id": 32, "title": "", "text": "# Introduction to Python Modules
Python offers a wide range of modules for performing various operations. Here, we are going to introduce some core modules like `numpy` for numerical operations, `pandas` for data manipulation, `requests` for making HTTP requests, and `os` for operating system-related tasks. Each module has its own documentation and examples, which are essential to understand for efficient programming."}
{"_id": 33, "title": "", "text": "### How to determine if an array is empty in JavaScript?
To check if an array is empty in JavaScript, you can use the .length property: ```javascript let array = []; if (array.length === 0) { console.log('Array is empty'); } else { console.log('Array is not empty'); } ``` This code checks if the length of the array is zero."}
{"_id": 34, "title": "", "text": "```javascript let list = []; if (list.length === 0) { console.log('List is empty'); } ```"}
{"_id": 35, "title": "", "text": "# Checking if a String is Empty in Python
In this section, we'll cover how to check if a string is empty in Python. An empty string is represented as `''`. You can use the `len()` function to check its length:
```python my_string = '' if len(my_string) == 0: print('String is empty') else: print('String is not empty') ```
Alternatively, you can use a simple conditional check:
```python my_string = '' if not my_string: print('String is empty') else: print('String is not empty') ```"}
{"_id": 36, "title": "", "text": "## How to Check if a File Exists in JavaScript?
You can use the Node.js `fs` module to check if a file exists in JavaScript. Here’s a simple example:
fs.access('path/to/file', fs.constants.F_OK, (err) => { if (err) { console.error('File does not exist'); } else { console.log('File exists'); } }); ```"}
{"_id": 38, "title": "", "text": "## How to Handle File Exceptions in Java To handle file exceptions in Java, you can use the `try-catch` block. Here is an example: ```java try { File file = new File(\"example.txt\"); if (file.exists() && !file.isDirectory()) { System.out.println(\"File exists\"); } } catch (IOException e) { e.printStackTrace(); } ```This code checks if the file exists and prints a message to the console if it does."}
{"_id": 39, "title": "", "text": "```markdown ### How do I concatenate two lists in Java?
To concatenate two lists in Java, you can use the `addAll()` method of the `ArrayList` class. Here's an example:
public class Main { public static void main(String[] args) { List list1 = new ArrayList<>(); list1.add(1); list1.add(2); List list2 = new ArrayList<>(); list2.add(3); list2.add(4);
Lists in Python are ordered collections of elements. They can contain elements of different types, but typically contain elements of the same type. Lists are mutable, meaning that they can be modified after creation. Here is how you can create a list:
```python my_list = [1, 2, 3, 4] ```
You can access elements using index notation:
```python print(my_list[0]) # Outputs: 1 ```"}
{"_id": 42, "title": "", "text": "### How do I change the size of legends in Matplotlib?
I have a plot with several lines, and the legend is too large. How can I change the font size or overall size of the legend?
```python import matplotlib.pyplot as plt plt.plot(x, y, label='data') plt.legend(fontsize='small') plt.show() ```
**Answer:** You can change the size of the legend by adjusting the `fontsize` parameter in the `legend` function as shown above. "}
{"_id": 43, "title": "", "text": "```javascript const data = [ { x: 1, y: 5 }, { x: 2, y: 10 }, { x: 3, y: 15 } ]; const svg = d3.select('svg'); const width = 500; const height = 300;
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+."}
{"_id": 45, "title": "", "text": "# How to change text color in C++ terminal?
I'm trying to print colored text to the terminal using C++. What libraries or methods can I use to achieve this? Any example code would be appreciated."}
{"_id": 46, "title": "", "text": "```python import os
# Check if the terminal supports color if os.name == 'nt': os.system('')
# This function does nothing related to coloring text print('Hello, World!') ```"}
{"_id": 47, "title": "", "text": "## Introduction to Python Printing
In Python, printing is performed using the `print()` function. The function can take any number of arguments, and it will convert them to a string representation and output them to the standard output (typically the console).
Example: ```python print('Hello, World!') ``` This prints 'Hello, World!' to the terminal."}
{"_id": 48, "title": "", "text": "### What is the difference between Python's list and tuple?
**Question:**
I am trying to understand the main differences between a list and a tuple in Python. Can someone explain?
**Answer:**
In Python, lists and tuples both are sequence data types that can store a collection of items. However, the key differences are:
- **List:** Lists are mutable, meaning you can change, add, or remove items after the list is created. - **Tuple:** Tuples are immutable, meaning once a tuple is created, you can't change its content.
Use a list when you need a mutable, ordered collection of items. Use a tuple when you need an immutable ordered collection of items."}
{"_id": 49, "title": "", "text": "```javascript // This JavaScript snippet shows array methods for adding elements let arr = [1, 2, 3]; arr.push(4); // Adds a single element to the end of the array arr = arr.concat([5, 6]); // Merges the array with another array console.log(arr); // Output: [1, 2, 3, 4, 5, 6] ```"}
{"_id": 50, "title": "", "text": "# Understanding Python's list.insert Method
The `insert()` method inserts a given element at a specified index in the list. It is different from `append` and `extend` as it allows placement of elements at any position within the list.
Refer to the [Python documentation](https://docs.python.org/3/tutorial/datastructures.html) for more details."}
{"_id": 51, "title": "", "text": "```markdown Title: How to get the current time in Python?
Question: I need to retrieve the current timestamp in my Python program. What's the best way to do this?
Answer: You can use the `datetime` module from the Python standard library to get the current time:
// To get the current directory const currentDir = process.cwd(); console.log(`Current directory: ${currentDir}`);
// To get the directory of the current file const fileDir = __dirname; console.log(`File directory: ${fileDir}`); ```"}
{"_id": 53, "title": "", "text": "## Python's time Module Official Documentation
The `time` module provides various time-related functions. For more extensive functionality, consider the `datetime` module. `time.time()` returns the current time in seconds since the Epoch as a floating point number."}
{"_id": 54, "title": "", "text": "### Question
How to create a new column in a Pandas DataFrame based on the values of another column?
I have a DataFrame in Python using Pandas. I want to create a new column that summarizes the information from an existing column. How can I achieve this?
### Answer
You can create a new column in a Pandas DataFrame by using the following method:
This code will create a new column in the DataFrame based on the values of `existing_column`."}
{"_id": 55, "title": "", "text": "```r # Renaming columns in an R data frame colnames(dataframe) <- c('new_name1', 'new_name2', 'new_name3') ```"}
{"_id": 56, "title": "", "text": "# DataFrame Creation
To create a DataFrame in pandas, you can use the `pd.DataFrame()` function, passing a dictionary where keys are the column names, and values are the data:
```python import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]} df = pd.DataFrame(data) print(df) ``` This will produce a DataFrame with the columns 'Name' and 'Age'."}
{"_id": 57, "title": "", "text": "### How to iterate over a Python dictionary
To iterate over a dictionary in Python, you can use a for loop. For example: ```python my_dict = {'a': 1, 'b': 2, 'c': 3} for key, value in my_dict.items(): print(f'Key: {key}, Value: {value}') ``` This will output: ``` Key: a, Value: 1 Key: b, Value: 2 Key: c, Value: 3 ``` "}
{"_id": 58, "title": "", "text": "```ruby # Removing a key from a Hash in Ruby hash = { a: 1, b: 2, c: 3 } hash.delete(:b) # {:a=>1, :c=>3} ```"}
{"_id": 59, "title": "", "text": "## Introduction to Python Dictionaries
A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values.
Example: ```python thisdict = { \"brand\": \"Ford\", \"model\": \"Mustang\", \"year\": 1964 } print(thisdict) ```"}
{"_id": 60, "title": "", "text": "### How to remove duplicates from a list in Python?
I'm trying to remove duplicates from a list and keep the order of elements. How can I achieve this in Python?