code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def complex_number(
self,
start_real: float = 0.0,
end_real: float = 1.0,
start_imag: float = 0.0,
end_imag: float = 1.0,
precision_real: int = 15,
precision_imag: int = 15,
) -> complex:
"""Generates a random complex number.
:param start_real... | Generates a random complex number.
:param start_real: Start real range.
:param end_real: End real range.
:param start_imag: Start imaginary range.
:param end_imag: End imaginary range.
:param precision_real: Round a real part of
number to a given precision.
... | complex_number | python | lk-geimfari/mimesis | mimesis/providers/numeric.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/numeric.py | MIT |
def complexes(
self,
start_real: float = 0,
end_real: float = 1,
start_imag: float = 0,
end_imag: float = 1,
precision_real: int = 15,
precision_imag: int = 15,
n: int = 10,
) -> list[complex]:
"""Generates a list of random complex numbers.
... | Generates a list of random complex numbers.
:param start_real: Start real range.
:param end_real: End real range.
:param start_imag: Start imaginary range.
:param end_imag: End imaginary range.
:param precision_real: Round a real part of
number to a given precision.... | complexes | python | lk-geimfari/mimesis | mimesis/providers/numeric.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/numeric.py | MIT |
def decimals(
self, start: float = 0.0, end: float = 1000.0, n: int = 10
) -> list[Decimal]:
"""Generates a list of decimal numbers.
:param start: Start range.
:param end: End range.
:param n: Length of the list.
:return: A list of :py:class:`decimal.Decimal` objects... | Generates a list of decimal numbers.
:param start: Start range.
:param end: End range.
:param n: Length of the list.
:return: A list of :py:class:`decimal.Decimal` objects.
| decimals | python | lk-geimfari/mimesis | mimesis/providers/numeric.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/numeric.py | MIT |
def matrix(
self,
m: int = 10,
n: int = 10,
num_type: NumType = NumType.FLOAT,
**kwargs: t.Any,
) -> Matrix:
"""Generates m x n matrix with a random numbers.
This method works with a variety of types,
so you can pass method-specific `**kwargs`.
... | Generates m x n matrix with a random numbers.
This method works with a variety of types,
so you can pass method-specific `**kwargs`.
:param m: Number of rows.
:param n: Number of columns.
:param num_type: NumType enum object.
:param kwargs: Other method-specific argumen... | matrix | python | lk-geimfari/mimesis | mimesis/providers/numeric.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/numeric.py | MIT |
def user(self) -> str:
"""Generates a random user.
:return: Path to user.
:Example:
/home/oretha
"""
user = self.random.choice(USERNAMES)
user = user.capitalize() if "win" in self.platform else user.lower()
return str(self._pathlib_home / user) | Generates a random user.
:return: Path to user.
:Example:
/home/oretha
| user | python | lk-geimfari/mimesis | mimesis/providers/path.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/path.py | MIT |
def users_folder(self) -> str:
"""Generates a random path to user's folders.
:return: Path.
:Example:
/home/taneka/Pictures
"""
user = self.user()
folder = self.random.choice(FOLDERS)
return str(self._pathlib_home / user / folder) | Generates a random path to user's folders.
:return: Path.
:Example:
/home/taneka/Pictures
| users_folder | python | lk-geimfari/mimesis | mimesis/providers/path.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/path.py | MIT |
def dev_dir(self) -> str:
"""Generates a random path to development directory.
:return: Path.
:Example:
/home/sherrell/Development/Python
"""
user = self.user()
folder = self.random.choice(["Development", "Dev"])
stack = self.random.choice(PROGRAMMIN... | Generates a random path to development directory.
:return: Path.
:Example:
/home/sherrell/Development/Python
| dev_dir | python | lk-geimfari/mimesis | mimesis/providers/path.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/path.py | MIT |
def project_dir(self) -> str:
"""Generates a random path to project directory.
:return: Path to project.
:Example:
/home/sherika/Development/Falcon/mercenary
"""
dev_dir = self.dev_dir()
project = self.random.choice(PROJECT_NAMES)
return str(self._pa... | Generates a random path to project directory.
:return: Path to project.
:Example:
/home/sherika/Development/Falcon/mercenary
| project_dir | python | lk-geimfari/mimesis | mimesis/providers/path.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/path.py | MIT |
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:
"""Initialize attributes.
:param args: Arguments.
:param kwargs: Keyword arguments.
"""
super().__init__(*args, **kwargs)
self._person = Person(
locale=Locale.EN,
seed=self.seed,
... | Initialize attributes.
:param args: Arguments.
:param kwargs: Keyword arguments.
| __init__ | python | lk-geimfari/mimesis | mimesis/providers/payment.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/payment.py | MIT |
def bitcoin_address(self) -> str:
"""Generates a random bitcoin address.
Keep in mind that although it generates **valid-looking** addresses,
it does not mean that they are actually valid.
:return: Bitcoin address.
:Example:
3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX
... | Generates a random bitcoin address.
Keep in mind that although it generates **valid-looking** addresses,
it does not mean that they are actually valid.
:return: Bitcoin address.
:Example:
3EktnHQD7RiAE6uzMj2ZifT9YgRrkSgzQX
| bitcoin_address | python | lk-geimfari/mimesis | mimesis/providers/payment.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/payment.py | MIT |
def ethereum_address(self) -> str:
"""Generates a random Ethereum address.
..note: The address will look like Ethereum address,
but keep in mind that it is not the valid address.
:return: Ethereum address.
:Example:
0xe8ece9e6ff7dba52d4c07d37418036a89af9698d
... | Generates a random Ethereum address.
..note: The address will look like Ethereum address,
but keep in mind that it is not the valid address.
:return: Ethereum address.
:Example:
0xe8ece9e6ff7dba52d4c07d37418036a89af9698d
| ethereum_address | python | lk-geimfari/mimesis | mimesis/providers/payment.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/payment.py | MIT |
def credit_card_number(self, card_type: CardType | None = None) -> str:
"""Generates a random credit card number.
:param card_type: Issuing Network. Default is Visa.
:return: Credit card number.
:raises NotImplementedError: if card_type not supported.
:Example:
4455... | Generates a random credit card number.
:param card_type: Issuing Network. Default is Visa.
:return: Credit card number.
:raises NotImplementedError: if card_type not supported.
:Example:
4455 5299 1152 2450
| credit_card_number | python | lk-geimfari/mimesis | mimesis/providers/payment.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/payment.py | MIT |
def credit_card_expiration_date(self, minimum: int = 16, maximum: int = 25) -> str:
"""Generates a random expiration date for credit card.
:param minimum: Date of issue.
:param maximum: Maximum of expiration_date.
:return: Expiration date of credit card.
:Example:
0... | Generates a random expiration date for credit card.
:param minimum: Date of issue.
:param maximum: Maximum of expiration_date.
:return: Expiration date of credit card.
:Example:
03/19.
| credit_card_expiration_date | python | lk-geimfari/mimesis | mimesis/providers/payment.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/payment.py | MIT |
def credit_card_owner(
self,
gender: Gender | None = None,
) -> dict[str, str]:
"""Generates a random credit card owner.
:param gender: Gender of the card owner.
:type gender: Gender enum.
:return:
"""
owner = {
"credit_card": self.credit_... | Generates a random credit card owner.
:param gender: Gender of the card owner.
:type gender: Gender enum.
:return:
| credit_card_owner | python | lk-geimfari/mimesis | mimesis/providers/payment.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/payment.py | MIT |
def birthdate(self, min_year: int = 1980, max_year: int = 2023) -> Date:
"""Generates a random birthdate as a :py:class:`datetime.date` object.
:param min_year: Maximum birth year.
:param max_year: Minimum birth year.
:return: Random date object.
"""
self._validate_birth... | Generates a random birthdate as a :py:class:`datetime.date` object.
:param min_year: Maximum birth year.
:param max_year: Minimum birth year.
:return: Random date object.
| birthdate | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def name(self, gender: Gender | None = None) -> str:
"""Generates a random name.
:param gender: Gender's enum object.
:return: Name.
:Example:
John.
"""
key = self.validate_enum(gender, Gender)
names: list[str] = self._extract(["names", key])
... | Generates a random name.
:param gender: Gender's enum object.
:return: Name.
:Example:
John.
| name | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def title(
self,
gender: Gender | None = None,
title_type: TitleType | None = None,
) -> str:
"""Generates a random title for name.
You can generate a random prefix or suffix
for name using this method.
:param gender: The gender.
:param title_type: T... | Generates a random title for name.
You can generate a random prefix or suffix
for name using this method.
:param gender: The gender.
:param title_type: TitleType enum object.
:return: The title.
:raises NonEnumerableError: if gender or title_type in incorrect format.
... | title | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def full_name(
self,
gender: Gender | None = None,
reverse: bool = False,
) -> str:
"""Generates a random full name.
:param reverse: Return reversed full name.
:param gender: Gender's enum object.
:return: Full name.
:Example:
Johann Wolf... | Generates a random full name.
:param reverse: Return reversed full name.
:param gender: Gender's enum object.
:return: Full name.
:Example:
Johann Wolfgang.
| full_name | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def username(
self, mask: str | None = None, drange: tuple[int, int] = (1800, 2100)
) -> str:
"""Generates a username by mask.
Masks allow you to generate a variety of usernames.
- **C** stands for capitalized username.
- **U** stands for uppercase username.
- **l**... | Generates a username by mask.
Masks allow you to generate a variety of usernames.
- **C** stands for capitalized username.
- **U** stands for uppercase username.
- **l** stands for lowercase username.
- **d** stands for digits in the username.
You can also use symbols ... | username | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def password(self, length: int = 8, hashed: bool = False) -> str:
"""Generates a password or hash of password.
:param length: Length of password.
:param hashed: SHA256 hash.
:return: Password or hash of password.
:Example:
k6dv2odff9#4h
"""
character... | Generates a password or hash of password.
:param length: Length of password.
:param hashed: SHA256 hash.
:return: Password or hash of password.
:Example:
k6dv2odff9#4h
| password | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def nationality(self, gender: Gender | None = None) -> str:
"""Generates a random nationality.
:param gender: Gender.
:return: Nationality.
:Example:
Russian
"""
nationalities: list[str] = self._extract(["nationality"])
# Separated by gender
... | Generates a random nationality.
:param gender: Gender.
:return: Nationality.
:Example:
Russian
| nationality | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def phone_number(self, mask: str = "", placeholder: str = "#") -> str:
"""Generates a random phone number.
:param mask: Mask for formatting number.
:param placeholder: A placeholder for a mask (default is #).
:return: Phone number.
:Example:
+7-(963)-409-11-22.
... | Generates a random phone number.
:param mask: Mask for formatting number.
:param placeholder: A placeholder for a mask (default is #).
:return: Phone number.
:Example:
+7-(963)-409-11-22.
| phone_number | python | lk-geimfari/mimesis | mimesis/providers/person.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/person.py | MIT |
def measure_unit(
self,
name: MeasureUnit | None = None,
symbol: bool = False,
) -> str:
"""Returns unit name from the International System of Units.
:param name: Enum object UnitName.
:param symbol: Return only symbol
:return: Unit.
"""
resul... | Returns unit name from the International System of Units.
:param name: Enum object UnitName.
:param symbol: Return only symbol
:return: Unit.
| measure_unit | python | lk-geimfari/mimesis | mimesis/providers/science.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/science.py | MIT |
def metric_prefix(
self, sign: MetricPrefixSign | None = None, symbol: bool = False
) -> str:
"""Generates a random prefix for the International System of Units.
:param sign: Sing of prefix (positive/negative).
:param symbol: Return the symbol of the prefix.
:return: Metric ... | Generates a random prefix for the International System of Units.
:param sign: Sing of prefix (positive/negative).
:param symbol: Return the symbol of the prefix.
:return: Metric prefix for SI measure units.
:raises NonEnumerableError: if sign is not supported.
:Example:
... | metric_prefix | python | lk-geimfari/mimesis | mimesis/providers/science.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/science.py | MIT |
def alphabet(self, lower_case: bool = False) -> list[str]:
"""Returns an alphabet for current locale.
:param lower_case: Return alphabet in lower case.
:return: Alphabet.
"""
case = "uppercase" if not lower_case else "lowercase"
alpha: list[str] = self._extract(["alphab... | Returns an alphabet for current locale.
:param lower_case: Return alphabet in lower case.
:return: Alphabet.
| alphabet | python | lk-geimfari/mimesis | mimesis/providers/text.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/text.py | MIT |
def text(self, quantity: int = 5) -> str:
"""Generates the text.
:param quantity: Quantity of sentences.
:return: Text.
"""
text = self._extract(["text"])
return " ".join(self.random.choices(text, k=quantity)) | Generates the text.
:param quantity: Quantity of sentences.
:return: Text.
| text | python | lk-geimfari/mimesis | mimesis/providers/text.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/text.py | MIT |
def words(self, quantity: int = 5) -> list[str]:
"""Generates a list of random words.
:param quantity: Quantity of words. Default is 5.
:return: Word list.
:Example:
[science, network, god, octopus, love]
"""
words = self._extract(["words"])
return s... | Generates a list of random words.
:param quantity: Quantity of words. Default is 5.
:return: Word list.
:Example:
[science, network, god, octopus, love]
| words | python | lk-geimfari/mimesis | mimesis/providers/text.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/text.py | MIT |
def _hex_to_rgb(color: str) -> tuple[int, ...]:
"""Converts hex color to RGB format.
:param color: Hex color.
:return: RGB tuple.
"""
color = color.lstrip("#") if color.startswith("#") else color
return tuple(int(color[i : i + 2], 16) for i in (0, 2, 4)) | Converts hex color to RGB format.
:param color: Hex color.
:return: RGB tuple.
| _hex_to_rgb | python | lk-geimfari/mimesis | mimesis/providers/text.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/text.py | MIT |
def hex_color(self, safe: bool = False) -> str:
"""Generates a random HEX color.
:param safe: Get safe Flat UI hex color.
:return: Hex color code.
:Example:
#d8346b
"""
if safe:
return self.random.choice(SAFE_COLORS)
return f"#{self.rand... | Generates a random HEX color.
:param safe: Get safe Flat UI hex color.
:return: Hex color code.
:Example:
#d8346b
| hex_color | python | lk-geimfari/mimesis | mimesis/providers/text.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/text.py | MIT |
def vehicle_registration_code(self, locale: Locale | None = None) -> str:
"""Returns vehicle registration code.
:param locale: Registration code for locale (country).
:return: Vehicle registration code.
"""
if locale:
return VRC_BY_LOCALES[locale.value]
retu... | Returns vehicle registration code.
:param locale: Registration code for locale (country).
:return: Vehicle registration code.
| vehicle_registration_code | python | lk-geimfari/mimesis | mimesis/providers/transport.py | https://github.com/lk-geimfari/mimesis/blob/master/mimesis/providers/transport.py | MIT |
def __init__(self, *, files: Iterable[Path]) -> None:
"""Find all files of all locales."""
self.files = files
self.before_total = 0
self.after_total = 0 | Find all files of all locales. | __init__ | python | lk-geimfari/mimesis | tasks/minifier.py | https://github.com/lk-geimfari/mimesis/blob/master/tasks/minifier.py | MIT |
def run(self) -> None:
"""Start json minimizer and exit when all json files were minimized."""
for file in self.files:
self.minify(file)
after = human_repr(self.after_total)
before = human_repr(self.before_total)
saved = human_repr(self.before_total - self.after_tota... | Start json minimizer and exit when all json files were minimized. | run | python | lk-geimfari/mimesis | tasks/minifier.py | https://github.com/lk-geimfari/mimesis/blob/master/tasks/minifier.py | MIT |
def validate_nip(nip):
"""Validate NIP.
:param nip: nip to validate
:return: True if nip is valid, False otherwise
"""
nip_digits = list(map(int, nip))
args = (6, 5, 7, 2, 3, 4, 5, 6, 7)
sum_v = sum(map(lambda x: x[0] * x[1], zip(args, nip_digits)))
checksum_digit = sum_v % 11
retur... | Validate NIP.
:param nip: nip to validate
:return: True if nip is valid, False otherwise
| validate_nip | python | lk-geimfari/mimesis | tests/test_builtins/test_poland_spec.py | https://github.com/lk-geimfari/mimesis/blob/master/tests/test_builtins/test_poland_spec.py | MIT |
def validate_pesel(pesel):
"""Validate PESEL.
:param pesel: pesel to validate
:return: True if pesel is valid, False otherwise
"""
pesel_digits = list(map(int, pesel))
args = (9, 7, 3, 1, 9, 7, 3, 1, 9, 7)
sum_v = sum(map(lambda x: x[0] * x[1], zip(args, pesel_digits)))
return pesel_dig... | Validate PESEL.
:param pesel: pesel to validate
:return: True if pesel is valid, False otherwise
| validate_pesel | python | lk-geimfari/mimesis | tests/test_builtins/test_poland_spec.py | https://github.com/lk-geimfari/mimesis/blob/master/tests/test_builtins/test_poland_spec.py | MIT |
def validate_regon(regon):
"""Validate REGON.
:param regon: regon to validate
:return: True if pesel is valid, False otherwise
"""
regon_digits = list(map(int, regon))
args = (8, 9, 2, 3, 4, 5, 6, 7)
sum_v = sum(map(lambda x: x[0] * x[1], zip(args, regon_digits)))
checksum_digit = sum_v... | Validate REGON.
:param regon: regon to validate
:return: True if pesel is valid, False otherwise
| validate_regon | python | lk-geimfari/mimesis | tests/test_builtins/test_poland_spec.py | https://github.com/lk-geimfari/mimesis/blob/master/tests/test_builtins/test_poland_spec.py | MIT |
def _chkpath(method, path):
"""Return an HTTP status for the given filesystem path."""
if method.lower() in ('put', 'delete'):
return 501, "Not Implemented" # TODO
elif method.lower() not in ('get', 'head'):
return 405, "Method Not Allowed"
elif os.path.isdir(pat... | Return an HTTP status for the given filesystem path. | _chkpath | python | renyijiu/douyin_downloader | local_file_adapter.py | https://github.com/renyijiu/douyin_downloader/blob/master/local_file_adapter.py | MIT |
def send(self, req, **kwargs): # pylint: disable=unused-argument
"""Return the file specified by the given request
@type req: C{PreparedRequest}
@todo: Should I bother filling `response.headers` and processing
If-Modified-Since and friends using `os.stat`?
"""
p... | Return the file specified by the given request
@type req: C{PreparedRequest}
@todo: Should I bother filling `response.headers` and processing
If-Modified-Since and friends using `os.stat`?
| send | python | renyijiu/douyin_downloader | local_file_adapter.py | https://github.com/renyijiu/douyin_downloader/blob/master/local_file_adapter.py | MIT |
def resize_image(origin_img, optimize_img, threshold):
"""
shrink image by size
:param origin_img:
:param optimize_img:
:param threshold:
:return:
"""
file_size = os.path.getsize(origin_img)
with Image.open(origin_img) as im:
if file_size > threshold:
width, heigh... |
shrink image by size
:param origin_img:
:param optimize_img:
:param threshold:
:return:
| resize_image | python | renyijiu/douyin_downloader | common/compression.py | https://github.com/renyijiu/douyin_downloader/blob/master/common/compression.py | MIT |
def crop_image(origin_img, optimize_img, x, y, width, height):
"""
crop imgae by size
:param origin image
:param optimize image
:param x , start point
:paran y , start point
:param width, the width of image
:param height, the height of image
"""
file_size = os.path.getsize(origi... |
crop imgae by size
:param origin image
:param optimize image
:param x , start point
:paran y , start point
:param width, the width of image
:param height, the height of image
| crop_image | python | renyijiu/douyin_downloader | common/compression.py | https://github.com/renyijiu/douyin_downloader/blob/master/common/compression.py | MIT |
def compute_reward(seq, actions, ignore_far_sim=True, temp_dist_thre=20, use_gpu=False):
"""
Compute diversity reward and representativeness reward
Args:
seq: sequence of features, shape (1, seq_len, dim)
actions: binary action sequence, shape (1, seq_len, 1)
ignore_far_sim (bool): ... |
Compute diversity reward and representativeness reward
Args:
seq: sequence of features, shape (1, seq_len, dim)
actions: binary action sequence, shape (1, seq_len, 1)
ignore_far_sim (bool): whether to ignore temporally distant similarity (default: True)
temp_dist_thre (int): th... | compute_reward | python | KaiyangZhou/pytorch-vsumm-reinforce | rewards.py | https://github.com/KaiyangZhou/pytorch-vsumm-reinforce/blob/master/rewards.py | MIT |
def generate_summary(ypred, cps, n_frames, nfps, positions, proportion=0.15, method='knapsack'):
"""Generate keyshot-based video summary i.e. a binary vector.
Args:
---------------------------------------------
- ypred: predicted importance scores.
- cps: change points, 2D matrix, each row contains ... | Generate keyshot-based video summary i.e. a binary vector.
Args:
---------------------------------------------
- ypred: predicted importance scores.
- cps: change points, 2D matrix, each row contains a segment.
- n_frames: original number of frames.
- nfps: number of frames per segment.
- po... | generate_summary | python | KaiyangZhou/pytorch-vsumm-reinforce | vsum_tools.py | https://github.com/KaiyangZhou/pytorch-vsumm-reinforce/blob/master/vsum_tools.py | MIT |
def evaluate_summary(machine_summary, user_summary, eval_metric='avg'):
"""Compare machine summary with user summary (keyshot-based).
Args:
--------------------------------
machine_summary and user_summary should be binary vectors of ndarray type.
eval_metric = {'avg', 'max'}
'avg' averages resu... | Compare machine summary with user summary (keyshot-based).
Args:
--------------------------------
machine_summary and user_summary should be binary vectors of ndarray type.
eval_metric = {'avg', 'max'}
'avg' averages results of comparing multiple human summaries.
'max' takes the maximum (best) o... | evaluate_summary | python | KaiyangZhou/pytorch-vsumm-reinforce | vsum_tools.py | https://github.com/KaiyangZhou/pytorch-vsumm-reinforce/blob/master/vsum_tools.py | MIT |
def check_brat_annotation_and_text_compatibility(brat_folder):
'''
Check if brat annotation and text files are compatible.
'''
dataset_type = os.path.basename(brat_folder)
print("Checking the validity of BRAT-formatted {0} set... ".format(dataset_type), end='')
text_filepaths = sorted(glob.glob... |
Check if brat annotation and text files are compatible.
| check_brat_annotation_and_text_compatibility | python | Franck-Dernoncourt/NeuroNER | neuroner/brat_to_conll.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/brat_to_conll.py | MIT |
def brat_to_conll(input_folder, output_filepath, tokenizer, language):
'''
Assumes '.txt' and '.ann' files are in the input_folder.
Checks for the compatibility between .txt and .ann at the same time.
'''
if tokenizer == 'spacy':
spacy_nlp = spacy.load(language)
elif tokenizer == 'stanfo... |
Assumes '.txt' and '.ann' files are in the input_folder.
Checks for the compatibility between .txt and .ann at the same time.
| brat_to_conll | python | Franck-Dernoncourt/NeuroNER | neuroner/brat_to_conll.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/brat_to_conll.py | MIT |
def generate_reference_text_file_for_conll(conll_input_filepath, conll_output_filepath, text_folder):
'''
generates reference text files and adds the corresponding filename and token offsets to conll file.
conll_input_filepath: path to a conll-formatted file without filename and token offsets
text_... |
generates reference text files and adds the corresponding filename and token offsets to conll file.
conll_input_filepath: path to a conll-formatted file without filename and token offsets
text_folder: folder to write the reference text file to
| generate_reference_text_file_for_conll | python | Franck-Dernoncourt/NeuroNER | neuroner/conll_to_brat.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/conll_to_brat.py | MIT |
def check_compatibility_between_conll_and_brat_text(conll_filepath, brat_folder):
'''
check if token offsets match between conll and brat .txt files.
conll_filepath: path to conll file
brat_folder: folder that contains the .txt (and .ann) files that are formatted according to brat.
... |
check if token offsets match between conll and brat .txt files.
conll_filepath: path to conll file
brat_folder: folder that contains the .txt (and .ann) files that are formatted according to brat.
| check_compatibility_between_conll_and_brat_text | python | Franck-Dernoncourt/NeuroNER | neuroner/conll_to_brat.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/conll_to_brat.py | MIT |
def conll_to_brat(conll_input_filepath, conll_output_filepath, brat_original_folder, brat_output_folder, overwrite=False):
'''
convert conll file in conll-filepath to brat annotations and output to brat_output_folder,
with reference to the existing text files in brat_original_folder
if brat_original_f... |
convert conll file in conll-filepath to brat annotations and output to brat_output_folder,
with reference to the existing text files in brat_original_folder
if brat_original_folder does not exist or contain any text file, then the text files are generated from conll files,
and conll file is updated w... | conll_to_brat | python | Franck-Dernoncourt/NeuroNER | neuroner/conll_to_brat.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/conll_to_brat.py | MIT |
def update_dataset(self, dataset_filepaths, dataset_types):
'''
dataset_filepaths : dictionary with keys 'train', 'valid', 'test', 'deploy'
Overwrites the data of type specified in dataset_types using the existing token_to_index, character_to_index, and label_to_index mappings.
'''
... |
dataset_filepaths : dictionary with keys 'train', 'valid', 'test', 'deploy'
Overwrites the data of type specified in dataset_types using the existing token_to_index, character_to_index, and label_to_index mappings.
| update_dataset | python | Franck-Dernoncourt/NeuroNER | neuroner/dataset.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/dataset.py | MIT |
def load_dataset(self, dataset_filepaths, parameters, token_to_vector=None):
'''
dataset_filepaths : dictionary with keys 'train', 'valid', 'test', 'deploy'
'''
start_time = time.time()
print('Load dataset... ', end='', flush=True)
if parameters['token_pretrained_embeddin... |
dataset_filepaths : dictionary with keys 'train', 'valid', 'test', 'deploy'
| load_dataset | python | Franck-Dernoncourt/NeuroNER | neuroner/dataset.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/dataset.py | MIT |
def plot_f1_vs_epoch(results, stats_graph_folder, metric, parameters, from_json=False):
'''
Takes results dictionary and saves the f1 vs epoch plot in stats_graph_folder.
from_json indicates if the results dictionary was loaded from results.json file.
In this case, dictionary indexes are mapped from str... |
Takes results dictionary and saves the f1 vs epoch plot in stats_graph_folder.
from_json indicates if the results dictionary was loaded from results.json file.
In this case, dictionary indexes are mapped from string to int.
metric can be f1_score or accuracy
| plot_f1_vs_epoch | python | Franck-Dernoncourt/NeuroNER | neuroner/evaluate.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/evaluate.py | MIT |
def result_to_plot(folder_name=None):
'''
Loads results.json file in the ../stats_graphs/folder_name, and plot f1 vs epoch.
Use for debugging purposes, or in case the program stopped due to error in plot_f1_vs_epoch.
'''
stats_graph_folder=os.path.join('.', 'stats_graphs')
if folder_name == None... |
Loads results.json file in the ../stats_graphs/folder_name, and plot f1 vs epoch.
Use for debugging purposes, or in case the program stopped due to error in plot_f1_vs_epoch.
| result_to_plot | python | Franck-Dernoncourt/NeuroNER | neuroner/evaluate.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/evaluate.py | MIT |
def remap_labels(y_pred, y_true, dataset, evaluation_mode='bio'):
'''
y_pred: list of predicted labels
y_true: list of gold labels
evaluation_mode: 'bio', 'token', or 'binary'
Both y_pred and y_true must use label indices and names specified in the dataset
# (dataset.unique_label_indices_of_int... |
y_pred: list of predicted labels
y_true: list of gold labels
evaluation_mode: 'bio', 'token', or 'binary'
Both y_pred and y_true must use label indices and names specified in the dataset
# (dataset.unique_label_indices_of_interest, dataset.unique_label_indices_of_interest).
| remap_labels | python | Franck-Dernoncourt/NeuroNER | neuroner/evaluate.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/evaluate.py | MIT |
def fetch_model(name):
"""
Fetch a pre-trained model and copy to a local "trained_models" folder
If name is provided, fetch from the package folder.
Args:
name (str): Name of a model folder.
"""
# get content from package and write to local dir
# model comprises of:
# dataset.p... |
Fetch a pre-trained model and copy to a local "trained_models" folder
If name is provided, fetch from the package folder.
Args:
name (str): Name of a model folder.
| fetch_model | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def _fetch(name, content_type=None):
"""
Load data or models from the package folder.
Args:
name (str): name of the resource
content_type (str): either "data" or "trained_models"
Returns:
fileset (dict): dictionary containing the file content
"""
package_name = 'neurone... |
Load data or models from the package folder.
Args:
name (str): name of the resource
content_type (str): either "data" or "trained_models"
Returns:
fileset (dict): dictionary containing the file content
| _fetch | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def _get_config_param(param_filepath=None):
"""
Get the parameters from the config file.
"""
param = {}
# If a parameter file is specified, load it
if param_filepath:
param_file_txt = configparser.ConfigParser()
param_file_txt.read(param_filepath, encoding="UTF-8")
neste... |
Get the parameters from the config file.
| _get_config_param | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def _clean_param_dtypes(param):
"""
Ensure data types are correct in the parameter dictionary.
Args:
param (dict): dictionary of parameter settings.
"""
# Set the data type
for k, v in param.items():
v = str(v)
# If the value is a list delimited with a comma, choose one... |
Ensure data types are correct in the parameter dictionary.
Args:
param (dict): dictionary of parameter settings.
| _clean_param_dtypes | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def load_parameters(**kwargs):
'''
Load parameters from the ini file if specified, take into account any
command line argument, and ensure that each parameter is cast to the
correct type.
Command line arguments take precedence over parameters specified in the
parameter file.
'''
param =... |
Load parameters from the ini file if specified, take into account any
command line argument, and ensure that each parameter is cast to the
correct type.
Command line arguments take precedence over parameters specified in the
parameter file.
| load_parameters | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def get_valid_dataset_filepaths(parameters):
"""
Get valid filepaths for the datasets.
"""
dataset_filepaths = {}
dataset_brat_folders = {}
for dataset_type in ['train', 'valid', 'test', 'deploy']:
dataset_filepaths[dataset_type] = os.path.join(parameters['dataset_text_folder'],
... |
Get valid filepaths for the datasets.
| get_valid_dataset_filepaths | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def _get_valid_dataset_filepaths(self, parameters, dataset_types=['train', 'valid', 'test', 'deploy']):
"""
Get paths for the datasets.
Args:
parameters (type): description.
dataset_types (type): description.
"""
dataset_filepaths = {}
dataset_bra... |
Get paths for the datasets.
Args:
parameters (type): description.
dataset_types (type): description.
| _get_valid_dataset_filepaths | python | Franck-Dernoncourt/NeuroNER | neuroner/neuromodel.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/neuromodel.py | MIT |
def trim_dataset_pickle(input_dataset_filepath, output_dataset_filepath=None, delete_token_mappings=False):
'''
Remove the dataset and labels from dataset.pickle.
If delete_token_mappings = True, then also remove token_to_index and index_to_token except for UNK.
'''
print("Trimming dataset.pickle..... |
Remove the dataset and labels from dataset.pickle.
If delete_token_mappings = True, then also remove token_to_index and index_to_token except for UNK.
| trim_dataset_pickle | python | Franck-Dernoncourt/NeuroNER | neuroner/prepare_pretrained_model.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/prepare_pretrained_model.py | MIT |
def trim_model_checkpoint(parameters_filepath, dataset_filepath, input_checkpoint_filepath,
output_checkpoint_filepath):
'''
Remove all token embeddings except UNK.
'''
parameters, _ = neuromodel.load_parameters(parameters_filepath=parameters_filepath)
dataset = pickle.load(open(dataset_filepat... |
Remove all token embeddings except UNK.
| trim_model_checkpoint | python | Franck-Dernoncourt/NeuroNER | neuroner/prepare_pretrained_model.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/prepare_pretrained_model.py | MIT |
def prepare_pretrained_model_for_restoring(output_folder_name, epoch_number,
model_name, delete_token_mappings=False):
'''
Copy the dataset.pickle, parameters.ini, and model checkpoint files after
removing the data used for training.
The dataset and labels are deleted from dataset.pickle by d... |
Copy the dataset.pickle, parameters.ini, and model checkpoint files after
removing the data used for training.
The dataset and labels are deleted from dataset.pickle by default. The only
information about the dataset that remain in the pretrained model
is the list of tokens that appears in t... | prepare_pretrained_model_for_restoring | python | Franck-Dernoncourt/NeuroNER | neuroner/prepare_pretrained_model.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/prepare_pretrained_model.py | MIT |
def check_contents_of_dataset_and_model_checkpoint(model_folder):
'''
Check the contents of dataset.pickle and model_xxx.ckpt.
model_folder: folder containing dataset.pickle and model_xxx.ckpt to be checked.
'''
dataset_filepath = os.path.join(model_folder, 'dataset.pickle')
dataset = pickle.lo... |
Check the contents of dataset.pickle and model_xxx.ckpt.
model_folder: folder containing dataset.pickle and model_xxx.ckpt to be checked.
| check_contents_of_dataset_and_model_checkpoint | python | Franck-Dernoncourt/NeuroNER | neuroner/prepare_pretrained_model.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/prepare_pretrained_model.py | MIT |
def order_dictionary(dictionary, mode, reverse=False):
'''
Order a dictionary by 'key' or 'value'.
mode should be either 'key' or 'value'
http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
'''
if mode =='key':
return collections.OrderedDict(sorted(dictionary.ite... |
Order a dictionary by 'key' or 'value'.
mode should be either 'key' or 'value'
http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value
| order_dictionary | python | Franck-Dernoncourt/NeuroNER | neuroner/utils.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils.py | MIT |
def reverse_dictionary(dictionary):
'''
http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping
http://stackoverflow.com/questions/25480089/right-way-to-initialize-an-ordereddict-using-its-constructor-such-that-it-retain
'''
#print('type(dictionary): {0}'.format(type(dictionary)))... |
http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping
http://stackoverflow.com/questions/25480089/right-way-to-initialize-an-ordereddict-using-its-constructor-such-that-it-retain
| reverse_dictionary | python | Franck-Dernoncourt/NeuroNER | neuroner/utils.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils.py | MIT |
def merge_dictionaries(*dict_args):
'''
http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
'''
result = {}
for dictionar... |
http://stackoverflow.com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
| merge_dictionaries | python | Franck-Dernoncourt/NeuroNER | neuroner/utils.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils.py | MIT |
def pad_list(old_list, padding_size, padding_value):
'''
http://stackoverflow.com/questions/3438756/some-built-in-to-pad-a-list-in-python
Example: pad_list([6,2,3], 5, 0) returns [6,2,3,0,0]
'''
assert padding_size >= len(old_list)
return old_list + [padding_value] * (padding_size-len(old_list)) |
http://stackoverflow.com/questions/3438756/some-built-in-to-pad-a-list-in-python
Example: pad_list([6,2,3], 5, 0) returns [6,2,3,0,0]
| pad_list | python | Franck-Dernoncourt/NeuroNER | neuroner/utils.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils.py | MIT |
def copytree(src, dst, symlinks=False, ignore=None):
'''
http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth
'''
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path... |
http://stackoverflow.com/questions/1868714/how-do-i-copy-an-entire-directory-of-files-into-an-existing-directory-using-pyth
| copytree | python | Franck-Dernoncourt/NeuroNER | neuroner/utils.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils.py | MIT |
def get_cmap():
'''
http://stackoverflow.com/questions/37517587/how-can-i-change-the-intensity-of-a-colormap-in-matplotlib
'''
cmap = cm.get_cmap('RdBu', 256) # set how many colors you want in color map
# modify colormap
alpha = 1.0
colors = []
for ind in range(cmap.N):
c = []
... |
http://stackoverflow.com/questions/37517587/how-can-i-change-the-intensity-of-a-colormap-in-matplotlib
| get_cmap | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_plots.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_plots.py | MIT |
def show_values(pc, fmt="%.2f", **kw):
'''
Heatmap with text in each cell with matplotlib's pyplot
Source: http://stackoverflow.com/a/25074150/395857
By HYRY
'''
pc.update_scalarmappable()
ax = pc.axes
for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.get_array()):
... |
Heatmap with text in each cell with matplotlib's pyplot
Source: http://stackoverflow.com/a/25074150/395857
By HYRY
| show_values | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_plots.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_plots.py | MIT |
def cm2inch(*tupl):
'''
Specify figure size in centimeter in matplotlib
Source: http://stackoverflow.com/a/22787457/395857
By gns-ank
'''
inch = 2.54
if type(tupl[0]) == tuple:
return tuple(i/inch for i in tupl[0])
else:
return tuple(i/inch for i in tupl) |
Specify figure size in centimeter in matplotlib
Source: http://stackoverflow.com/a/22787457/395857
By gns-ank
| cm2inch | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_plots.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_plots.py | MIT |
def heatmap(AUC, title, xlabel, ylabel, xticklabels, yticklabels, figure_width=40, figure_height=20, correct_orientation=False, cmap='RdBu', fmt="%.2f", graph_filepath='', normalize=False, remove_diagonal=False):
'''
Inspired by:
- http://stackoverflow.com/a/16124677/395857
- http://stackoverflow.com/a/... |
Inspired by:
- http://stackoverflow.com/a/16124677/395857
- http://stackoverflow.com/a/25074150/395857
| heatmap | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_plots.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_plots.py | MIT |
def plot_classification_report(classification_report, title='Classification report ', cmap='RdBu', from_conll_json=False):
'''
Plot scikit-learn classification report.
Extension based on http://stackoverflow.com/a/31689645/395857
'''
classes = []
plotMat = []
support = []
class_names = [... |
Plot scikit-learn classification report.
Extension based on http://stackoverflow.com/a/31689645/395857
| plot_classification_report | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_plots.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_plots.py | MIT |
def variable_summaries(var):
'''
Attach a lot of summaries to a Tensor (for TensorBoard visualization).
From https://www.tensorflow.org/get_started/summaries_and_tensorboard
'''
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
with t... |
Attach a lot of summaries to a Tensor (for TensorBoard visualization).
From https://www.tensorflow.org/get_started/summaries_and_tensorboard
| variable_summaries | python | Franck-Dernoncourt/NeuroNER | neuroner/utils_tf.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/utils_tf.py | MIT |
def parse_arguments(arguments=None):
"""
Parse the NeuroNER arguments
arguments:
arguments the arguments, optionally given as argument
"""
parser = argparse.ArgumentParser(description='''NeuroNER CLI''', formatter_class=RawTextHelpFormatter)
parser.add_argument('--parameters_filepath'... |
Parse the NeuroNER arguments
arguments:
arguments the arguments, optionally given as argument
| parse_arguments | python | Franck-Dernoncourt/NeuroNER | neuroner/__main__.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/__main__.py | MIT |
def main(argv=sys.argv):
''' NeuroNER main method
Args:
parameters_filepath the path to the parameters file
output_folder the path to the output folder
'''
arguments = parse_arguments(argv[1:])
# fetch data and models from the package
if arguments['fetch_data'] or arguments['fe... | NeuroNER main method
Args:
parameters_filepath the path to the parameters file
output_folder the path to the output folder
| main | python | Franck-Dernoncourt/NeuroNER | neuroner/__main__.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/neuroner/__main__.py | MIT |
def test_ProvideOutputDir_CorrectlyOutputsToDir(self):
"""
Sanity test to check if all proper model output files are created in the output folder
"""
nn = neuromodel.NeuroNER(output_folder=self.outputFolder, parameters_filepath=self.test_param_file)
nn.fit()
# find the n... |
Sanity test to check if all proper model output files are created in the output folder
| test_ProvideOutputDir_CorrectlyOutputsToDir | python | Franck-Dernoncourt/NeuroNER | test/test_main.py | https://github.com/Franck-Dernoncourt/NeuroNER/blob/master/test/test_main.py | MIT |
def connect(host="localhost", user=None, password="",
db=None, port=3306, unix_socket=None,
charset='', sql_mode=None,
read_default_file=None, conv=decoders, use_unicode=None,
client_flag=0, cursorclass=Cursor, init_command=None,
connect_timeout=None, read_def... | See connections.Connection.__init__() for information about
defaults. | connect | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def ensure_closed(self):
"""Send quit command and then close socket connection"""
if self._writer is None:
# connection has been closed
return
send_data = struct.pack('<i', 1) + bytes([COMMAND.COM_QUIT])
self._writer.write(send_data)
await self._writ... | Send quit command and then close socket connection | ensure_closed | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
def escape(self, obj):
""" Escape whatever value you pass to it"""
if isinstance(obj, str):
return "'" + self.escape_string(obj) + "'"
if isinstance(obj, bytes):
return escape_bytes_prefixed(obj)
return escape_item(obj, self._charset) | Escape whatever value you pass to it | escape | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
def cursor(self, *cursors):
"""Instantiates and returns a cursor
By default, :class:`Cursor` is returned. It is possible to also give a
custom cursor through the cursor_class parameter, but it needs to
be a subclass of :class:`Cursor`
:param cursor: custom cursor class.
... | Instantiates and returns a cursor
By default, :class:`Cursor` is returned. It is possible to also give a
custom cursor through the cursor_class parameter, but it needs to
be a subclass of :class:`Cursor`
:param cursor: custom cursor class.
:returns: instance of cursor, by defa... | cursor | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def ping(self, reconnect=True):
"""Check if the server is alive"""
if self._writer is None and self._reader is None:
if reconnect:
await self._connect()
reconnect = False
else:
raise Error("Already closed")
try:
... | Check if the server is alive | ping | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def set_charset(self, charset):
"""Sets the character set for the current connection"""
# Make sure charset is supported.
encoding = charset_by_name(charset).encoding
await self._execute_command(COMMAND.COM_QUERY, "SET NAMES %s"
% self.escape(cha... | Sets the character set for the current connection | set_charset | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
def write_packet(self, payload):
"""Writes an entire "mysql packet" in its entirety to the network
addings its length and sequence number.
"""
# Internal note: when you build packet manually and calls
# _write_bytes() directly, you should set self._next_seq_id properly.
d... | Writes an entire "mysql packet" in its entirety to the network
addings its length and sequence number.
| write_packet | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def _read_packet(self, packet_type=MysqlPacket):
"""Read an entire "mysql packet" in its entirety from the network
and return a MysqlPacket type that represents the results.
"""
buff = b''
while True:
try:
packet_header = await self._read_bytes(4... | Read an entire "mysql packet" in its entirety from the network
and return a MysqlPacket type that represents the results.
| _read_packet | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def _read_rowdata_packet(self):
"""Read a rowdata packet for each data row in the result set."""
rows = []
while True:
packet = await self.connection._read_packet()
if self._check_packet_is_eof(packet):
# release reference to kill cyclic reference.
... | Read a rowdata packet for each data row in the result set. | _read_rowdata_packet | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def _get_descriptions(self):
"""Read a column descriptor packet for each column in the result."""
self.fields = []
self.converters = []
use_unicode = self.connection.use_unicode
conn_encoding = self.connection.encoding
description = []
for i in range(self.fi... | Read a column descriptor packet for each column in the result. | _get_descriptions | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
async def send_data(self):
"""Send data packets from the local file to the server"""
self.connection._ensure_alive()
conn = self.connection
try:
await self._open_file()
with self._file_object:
chunk_size = MAX_PACKET_LEN
while True... | Send data packets from the local file to the server | send_data | python | aio-libs/aiomysql | aiomysql/connection.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/connection.py | MIT |
def __init__(self, connection, echo=False):
"""Do not create an instance of a Cursor yourself. Call
connections.Connection.cursor().
"""
self._connection = connection
self._loop = self._connection.loop
self._description = None
self._rownumber = 0
self._row... | Do not create an instance of a Cursor yourself. Call
connections.Connection.cursor().
| __init__ | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def close(self):
"""Closing a cursor just exhausts all remaining data."""
conn = self._connection
if conn is None:
return
try:
while (await self.nextset()):
pass
finally:
self._connection = None | Closing a cursor just exhausts all remaining data. | close | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
def mogrify(self, query, args=None):
""" Returns the exact string that is sent to the database by calling
the execute() method. This method follows the extension to the DB
API 2.0 followed by Psycopg.
:param query: ``str`` sql statement
:param args: ``tuple`` or ``list`` of argu... | Returns the exact string that is sent to the database by calling
the execute() method. This method follows the extension to the DB
API 2.0 followed by Psycopg.
:param query: ``str`` sql statement
:param args: ``tuple`` or ``list`` of arguments for sql query
| mogrify | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def execute(self, query, args=None):
"""Executes the given operation
Executes the given operation substituting any markers with
the given parameters.
For example, getting all rows where id is 5:
cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,))
:param quer... | Executes the given operation
Executes the given operation substituting any markers with
the given parameters.
For example, getting all rows where id is 5:
cursor.execute("SELECT * FROM t1 WHERE id = %s", (5,))
:param query: ``str`` sql statement
:param args: ``tuple`... | execute | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def executemany(self, query, args):
"""Execute the given operation multiple times
The executemany() method will execute the operation iterating
over the list of parameters in seq_params.
Example: Inserting 3 new employees and their phone number
data = [
... | Execute the given operation multiple times
The executemany() method will execute the operation iterating
over the list of parameters in seq_params.
Example: Inserting 3 new employees and their phone number
data = [
('Jane','555-001'),
('Joe', '555-0... | executemany | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def callproc(self, procname, args=()):
"""Execute stored procedure procname with args
Compatibility warning: PEP-249 specifies that any modified
parameters must be returned. This is currently impossible
as they are only available by storing them in a server
variable and th... | Execute stored procedure procname with args
Compatibility warning: PEP-249 specifies that any modified
parameters must be returned. This is currently impossible
as they are only available by storing them in a server
variable and then retrieved by a query. Since stored
procedures... | callproc | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
def fetchmany(self, size=None):
"""Returns the next set of rows of a query result, returning a
list of tuples. When no more rows are available, it returns an
empty list.
The number of rows returned can be specified using the size argument,
which defaults to one
:param s... | Returns the next set of rows of a query result, returning a
list of tuples. When no more rows are available, it returns an
empty list.
The number of rows returned can be specified using the size argument,
which defaults to one
:param size: ``int`` number of rows to return
... | fetchmany | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
def fetchall(self):
"""Returns all rows of a query result set
:returns: ``list`` of fetched rows
"""
self._check_executed()
fut = self._loop.create_future()
if self._rows is None:
fut.set_result([])
return fut
if self._rownumber:
... | Returns all rows of a query result set
:returns: ``list`` of fetched rows
| fetchall | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
def scroll(self, value, mode='relative'):
"""Scroll the cursor in the result set to a new position according
to mode.
If mode is relative (default), value is taken as offset to the
current position in the result set, if set to absolute, value
states an absolute target position.... | Scroll the cursor in the result set to a new position according
to mode.
If mode is relative (default), value is taken as offset to the
current position in the result set, if set to absolute, value
states an absolute target position. An IndexError should be raised in
case a scr... | scroll | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def fetchall(self):
"""Fetch all, as per MySQLdb. Pretty useless for large queries, as
it is buffered.
"""
rows = []
while True:
row = await self.fetchone()
if row is None:
break
rows.append(row)
return rows | Fetch all, as per MySQLdb. Pretty useless for large queries, as
it is buffered.
| fetchall | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def fetchmany(self, size=None):
"""Returns the next set of rows of a query result, returning a
list of tuples. When no more rows are available, it returns an
empty list.
The number of rows returned can be specified using the size argument,
which defaults to one
:p... | Returns the next set of rows of a query result, returning a
list of tuples. When no more rows are available, it returns an
empty list.
The number of rows returned can be specified using the size argument,
which defaults to one
:param size: ``int`` number of rows to return
... | fetchmany | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
async def scroll(self, value, mode='relative'):
"""Scroll the cursor in the result set to a new position
according to mode . Same as :meth:`Cursor.scroll`, but move cursor
on server side one by one row. If you want to move 20 rows forward
scroll will make 20 queries to move cursor. Curre... | Scroll the cursor in the result set to a new position
according to mode . Same as :meth:`Cursor.scroll`, but move cursor
on server side one by one row. If you want to move 20 rows forward
scroll will make 20 queries to move cursor. Currently only forward
scrolling is supported.
... | scroll | python | aio-libs/aiomysql | aiomysql/cursors.py | https://github.com/aio-libs/aiomysql/blob/master/aiomysql/cursors.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.