nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gwastro/pycbc | 1e1c85534b9dba8488ce42df693230317ca63dea | pycbc/workflow/core.py | python | Executable.add_ini_opts | (self, cp, sec) | Add job-specific options from configuration file.
Parameters
-----------
cp : ConfigParser object
The ConfigParser object holding the workflow configuration settings
sec : string
The section containing options for this job. | Add job-specific options from configuration file. | [
"Add",
"job",
"-",
"specific",
"options",
"from",
"configuration",
"file",
"."
] | def add_ini_opts(self, cp, sec):
"""Add job-specific options from configuration file.
Parameters
-----------
cp : ConfigParser object
The ConfigParser object holding the workflow configuration settings
sec : string
The section containing options for this job.
"""
for opt in cp.options(sec):
value = cp.get(sec, opt).strip()
opt = '--%s' %(opt,)
if opt in self.file_input_options:
# This now expects the option to be a file
# Check is we have a list of files
values = [path for path in value.split(' ') if path]
self.common_raw_options.append(opt)
self.common_raw_options.append(' ')
# Get LFN and PFN
for path in values:
# Here I decide if the path is URL or
# IFO:/path/to/file or IFO:url://path/to/file
# That's somewhat tricksy as we used : as delimiter
split_path = path.split(':', 1)
if len(split_path) == 1:
ifo = None
path = path
else:
# Have I split a URL or not?
if split_path[1].startswith('//'):
# URL
ifo = None
path = path
else:
#IFO:path or IFO:URL
ifo = split_path[0]
path = split_path[1]
# If the file exists make sure to use the
# fill path as a file:// URL
if os.path.isfile(path):
curr_pfn = urljoin('file:',
pathname2url(os.path.abspath(path)))
else:
curr_pfn = path
curr_file = resolve_url_to_file(curr_pfn)
self.common_input_files.append(curr_file)
if ifo:
self.common_raw_options.append(ifo + ':')
self.common_raw_options.append(curr_file.dax_repr)
else:
self.common_raw_options.append(curr_file.dax_repr)
self.common_raw_options.append(' ')
elif opt in self.time_dependent_options:
# There is a possibility of time-dependent, file options.
# For now we will avoid supporting that complication unless
# it is needed. This would require resolving the file first
# in this function, and then dealing with the time-dependent
# stuff later.
self.unresolved_td_options[opt] = value
else:
self.common_options += [opt, value] | [
"def",
"add_ini_opts",
"(",
"self",
",",
"cp",
",",
"sec",
")",
":",
"for",
"opt",
"in",
"cp",
".",
"options",
"(",
"sec",
")",
":",
"value",
"=",
"cp",
".",
"get",
"(",
"sec",
",",
"opt",
")",
".",
"strip",
"(",
")",
"opt",
"=",
"'--%s'",
"%... | https://github.com/gwastro/pycbc/blob/1e1c85534b9dba8488ce42df693230317ca63dea/pycbc/workflow/core.py#L326-L391 | ||
Kozea/WeasyPrint | 6cce2978165134e37683cb5b3d156cac6a11a7f9 | weasyprint/css/validation/properties.py | python | column_width | (token) | ``column-width`` property validation. | ``column-width`` property validation. | [
"column",
"-",
"width",
"property",
"validation",
"."
] | def column_width(token):
"""``column-width`` property validation."""
length = get_length(token, negative=False)
if length:
return length
keyword = get_keyword(token)
if keyword == 'auto':
return keyword | [
"def",
"column_width",
"(",
"token",
")",
":",
"length",
"=",
"get_length",
"(",
"token",
",",
"negative",
"=",
"False",
")",
"if",
"length",
":",
"return",
"length",
"keyword",
"=",
"get_keyword",
"(",
"token",
")",
"if",
"keyword",
"==",
"'auto'",
":",... | https://github.com/Kozea/WeasyPrint/blob/6cce2978165134e37683cb5b3d156cac6a11a7f9/weasyprint/css/validation/properties.py#L430-L437 | ||
home-assistant/supervisor | 69c2517d5211b483fdfe968b0a2b36b672ee7ab2 | supervisor/store/data.py | python | StoreData._read_addons_folder | (self, path: Path, repository: dict) | Read data from add-ons folder. | Read data from add-ons folder. | [
"Read",
"data",
"from",
"add",
"-",
"ons",
"folder",
"."
] | def _read_addons_folder(self, path: Path, repository: dict) -> None:
"""Read data from add-ons folder."""
if not (addon_list := self._find_addons(path, repository)):
return
for addon in addon_list:
try:
addon_config = read_json_or_yaml_file(addon)
except ConfigurationFileError:
_LOGGER.warning("Can't read %s from repository %s", addon, repository)
continue
# validate
try:
addon_config = SCHEMA_ADDON_CONFIG(addon_config)
except vol.Invalid as ex:
_LOGGER.warning(
"Can't read %s: %s", addon, humanize_error(addon_config, ex)
)
continue
# Generate slug
addon_slug = f"{repository}_{addon_config[ATTR_SLUG]}"
# store
addon_config[ATTR_REPOSITORY] = repository
addon_config[ATTR_LOCATON] = str(addon.parent)
addon_config[ATTR_TRANSLATIONS] = self._read_addon_translations(
addon.parent
)
self.addons[addon_slug] = addon_config | [
"def",
"_read_addons_folder",
"(",
"self",
",",
"path",
":",
"Path",
",",
"repository",
":",
"dict",
")",
"->",
"None",
":",
"if",
"not",
"(",
"addon_list",
":=",
"self",
".",
"_find_addons",
"(",
"path",
",",
"repository",
")",
")",
":",
"return",
"fo... | https://github.com/home-assistant/supervisor/blob/69c2517d5211b483fdfe968b0a2b36b672ee7ab2/supervisor/store/data.py#L122-L152 | ||
danielplohmann/apiscout | 8622b54302cb2712fe35ce971e77d1f3d5849a2a | apiscout/db_builder/pefile.py | python | PE.parse_export_directory | (self, rva, size, forwarded_only=False) | return ExportDirData(struct=export_dir, symbols=exports,
name=self.get_string_at_rva(export_dir.Name)) | Parse the export directory.
Given the RVA of the export directory, it will process all
its entries.
The exports will be made available as a list of ExportData
instances in the 'IMAGE_DIRECTORY_ENTRY_EXPORT' PE attribute. | Parse the export directory. | [
"Parse",
"the",
"export",
"directory",
"."
] | def parse_export_directory(self, rva, size, forwarded_only=False):
"""Parse the export directory.
Given the RVA of the export directory, it will process all
its entries.
The exports will be made available as a list of ExportData
instances in the 'IMAGE_DIRECTORY_ENTRY_EXPORT' PE attribute.
"""
try:
export_dir = self.__unpack_data__(
self.__IMAGE_EXPORT_DIRECTORY_format__,
self.get_data( rva, Structure(self.__IMAGE_EXPORT_DIRECTORY_format__).sizeof() ),
file_offset = self.get_offset_from_rva(rva) )
except PEFormatError:
self.__warnings.append(
'Error parsing export directory at RVA: 0x%x' % ( rva ) )
return
if not export_dir:
return
# We keep track of the bytes left in the file and use it to set a upper
# bound in the number of items that can be read from the different
# arrays.
def length_until_eof(rva):
return len(self.__data__) - self.get_offset_from_rva(rva)
try:
address_of_names = self.get_data(
export_dir.AddressOfNames,
min(length_until_eof(export_dir.AddressOfNames),
export_dir.NumberOfNames*4))
address_of_name_ordinals = self.get_data(
export_dir.AddressOfNameOrdinals,
min(length_until_eof(export_dir.AddressOfNameOrdinals),
export_dir.NumberOfNames*4))
address_of_functions = self.get_data(
export_dir.AddressOfFunctions,
min(length_until_eof(export_dir.AddressOfFunctions),
export_dir.NumberOfFunctions*4))
except PEFormatError:
self.__warnings.append(
'Error parsing export directory at RVA: 0x%x' % ( rva ) )
return
exports = []
max_failed_entries_before_giving_up = 10
section = self.get_section_by_rva(export_dir.AddressOfNames)
# Overly generous upper bound
safety_boundary = len(self.__data__)
if section:
safety_boundary = (
section.VirtualAddress + len(section.get_data()) -
export_dir.AddressOfNames)
symbol_counts = collections.defaultdict(int)
export_parsing_loop_completed_normally = True
for i in range(min(export_dir.NumberOfNames, int(safety_boundary / 4))):
symbol_ordinal = self.get_word_from_data(
address_of_name_ordinals, i)
if (symbol_ordinal is not None and
symbol_ordinal*4 < len(address_of_functions)):
symbol_address = self.get_dword_from_data(
address_of_functions, symbol_ordinal)
else:
# Corrupt? a bad pointer... we assume it's all
# useless, no exports
return None
if symbol_address is None or symbol_address == 0:
continue
# If the function's RVA points within the export directory
# it will point to a string with the forwarded symbol's string
# instead of pointing the the function start address.
if symbol_address >= rva and symbol_address < rva+size:
forwarder_str = self.get_string_at_rva(symbol_address)
try:
forwarder_offset = self.get_offset_from_rva( symbol_address )
except PEFormatError:
continue
else:
if forwarded_only:
continue
forwarder_str = None
forwarder_offset = None
symbol_name_address = self.get_dword_from_data(address_of_names, i)
if symbol_name_address is None:
max_failed_entries_before_giving_up -= 1
if max_failed_entries_before_giving_up <= 0:
export_parsing_loop_completed_normally = False
break
symbol_name = self.get_string_at_rva(symbol_name_address, MAX_SYMBOL_NAME_LENGTH)
if not is_valid_function_name(symbol_name):
export_parsing_loop_completed_normally = False
break
try:
symbol_name_offset = self.get_offset_from_rva(symbol_name_address)
except PEFormatError:
max_failed_entries_before_giving_up -= 1
if max_failed_entries_before_giving_up <= 0:
export_parsing_loop_completed_normally = False
break
try:
symbol_name_offset = self.get_offset_from_rva( symbol_name_address )
except PEFormatError:
max_failed_entries_before_giving_up -= 1
if max_failed_entries_before_giving_up <= 0:
export_parsing_loop_completed_normally = False
break
continue
# File 0b1d3d3664915577ab9a32188d29bbf3542b86c7b9ce333e245496c3018819f1
# was being parsed as potentially containing millions of exports.
# Checking for duplicates addresses the issue.
symbol_counts[(symbol_name, symbol_address)] += 1
if symbol_counts[(symbol_name, symbol_address)] > 10:
self.__warnings.append(
'Export directory contains more than 10 repeated entries '
'({:s}, 0x{:x}). Assuming corrupt.'.format(
symbol_name, symbol_address))
break
elif len(symbol_counts) > self.max_symbol_exports:
self.__warnings.append(
'Export directory contains more than {} symbol entries. '
'Assuming corrupt.'.format(self.max_symbol_exports))
break
exports.append(
ExportData(
pe = self,
ordinal = export_dir.Base+symbol_ordinal,
ordinal_offset = self.get_offset_from_rva( export_dir.AddressOfNameOrdinals + 2*i ),
address = symbol_address,
address_offset = self.get_offset_from_rva( export_dir.AddressOfFunctions + 4*symbol_ordinal ),
name = symbol_name,
name_offset = symbol_name_offset,
forwarder = forwarder_str,
forwarder_offset = forwarder_offset ))
if not export_parsing_loop_completed_normally:
self.__warnings.append(
'RVA AddressOfNames in the export directory points to an invalid address: %x' %
export_dir.AddressOfNames)
ordinals = {exp.ordinal for exp in exports}
max_failed_entries_before_giving_up = 10
section = self.get_section_by_rva(export_dir.AddressOfFunctions)
# Overly generous upper bound
safety_boundary = len(self.__data__)
if section:
safety_boundary = (
section.VirtualAddress + len(section.get_data()) -
export_dir.AddressOfFunctions)
symbol_counts = collections.defaultdict(int)
export_parsing_loop_completed_normally = True
for idx in range(min(
export_dir.NumberOfFunctions,
int(safety_boundary / 4))):
if not idx+export_dir.Base in ordinals:
try:
symbol_address = self.get_dword_from_data(
address_of_functions, idx)
except PEFormatError:
symbol_address = None
if symbol_address is None:
max_failed_entries_before_giving_up -= 1
if max_failed_entries_before_giving_up <= 0:
export_parsing_loop_completed_normally = False
break
if symbol_address == 0:
continue
# Checking for forwarder again.
if symbol_address is not None and symbol_address >= rva and symbol_address < rva+size:
forwarder_str = self.get_string_at_rva(symbol_address)
else:
forwarder_str = None
# File 0b1d3d3664915577ab9a32188d29bbf3542b86c7b9ce333e245496c3018819f1
# was being parsed as potentially containing millions of exports.
# Checking for duplicates addresses the issue.
symbol_counts[symbol_address] += 1
if symbol_counts[symbol_address] > 10:
# if most_common and most_common[0][1] > 10:
self.__warnings.append(
'Export directory contains more than 10 repeated '
'ordinal entries (0x{:x}). Assuming corrupt.'.format(
symbol_address))
break
elif len(symbol_counts) > self.max_symbol_exports:
self.__warnings.append(
'Export directory contains more than {} ordinal entries. Assuming corrupt.'.format(
self.max_symbol_exports))
break
exports.append(
ExportData(
ordinal = export_dir.Base+idx,
address = symbol_address,
name = None,
forwarder = forwarder_str))
if not export_parsing_loop_completed_normally:
self.__warnings.append(
'RVA AddressOfFunctions in the export directory points to an invalid address: %x' %
export_dir.AddressOfFunctions)
return
if not exports and export_dir.all_zeroes():
return None
return ExportDirData(struct=export_dir, symbols=exports,
name=self.get_string_at_rva(export_dir.Name)) | [
"def",
"parse_export_directory",
"(",
"self",
",",
"rva",
",",
"size",
",",
"forwarded_only",
"=",
"False",
")",
":",
"try",
":",
"export_dir",
"=",
"self",
".",
"__unpack_data__",
"(",
"self",
".",
"__IMAGE_EXPORT_DIRECTORY_format__",
",",
"self",
".",
"get_d... | https://github.com/danielplohmann/apiscout/blob/8622b54302cb2712fe35ce971e77d1f3d5849a2a/apiscout/db_builder/pefile.py#L3910-L4134 | |
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | src/transformers/models/tapas/tokenization_tapas.py | python | TapasTokenizer.encode_plus | (
self,
table: "pd.DataFrame",
query: Optional[
Union[
TextInput,
PreTokenizedInput,
EncodedInput,
]
] = None,
answer_coordinates: Optional[List[Tuple]] = None,
answer_text: Optional[List[TextInput]] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TapasTruncationStrategy] = False,
max_length: Optional[int] = None,
pad_to_multiple_of: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
**kwargs
) | return self._encode_plus(
table=table,
query=query,
answer_coordinates=answer_coordinates,
answer_text=answer_text,
add_special_tokens=add_special_tokens,
truncation=truncation,
padding=padding,
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors=return_tensors,
return_token_type_ids=return_token_type_ids,
return_attention_mask=return_attention_mask,
return_special_tokens_mask=return_special_tokens_mask,
return_offsets_mapping=return_offsets_mapping,
return_length=return_length,
verbose=verbose,
**kwargs,
) | Prepare a table and a string for the model.
Args:
table (`pd.DataFrame`):
Table containing tabular data. Note that all cell values must be text. Use *.astype(str)* on a Pandas
dataframe to convert it to string.
query (`str` or `List[str]`):
Question related to a table to be encoded.
answer_coordinates (`List[Tuple]` or `List[List[Tuple]]`, *optional*):
Answer coordinates of each table-question pair in the batch. The answer_coordinates must be a single
list of one or more tuples. Each tuple must be a (row_index, column_index) pair. The first data row
(not the column header row) has index 0. The first column has index 0.
answer_text (`List[str]` or `List[List[str]]`, *optional*):
Answer text of each table-question pair in the batch. The answer_text must be a single list of one or
more strings. Each string must be the answer text of a corresponding answer coordinate. | Prepare a table and a string for the model. | [
"Prepare",
"a",
"table",
"and",
"a",
"string",
"for",
"the",
"model",
"."
] | def encode_plus(
self,
table: "pd.DataFrame",
query: Optional[
Union[
TextInput,
PreTokenizedInput,
EncodedInput,
]
] = None,
answer_coordinates: Optional[List[Tuple]] = None,
answer_text: Optional[List[TextInput]] = None,
add_special_tokens: bool = True,
padding: Union[bool, str, PaddingStrategy] = False,
truncation: Union[bool, str, TapasTruncationStrategy] = False,
max_length: Optional[int] = None,
pad_to_multiple_of: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False,
return_length: bool = False,
verbose: bool = True,
**kwargs
) -> BatchEncoding:
"""
Prepare a table and a string for the model.
Args:
table (`pd.DataFrame`):
Table containing tabular data. Note that all cell values must be text. Use *.astype(str)* on a Pandas
dataframe to convert it to string.
query (`str` or `List[str]`):
Question related to a table to be encoded.
answer_coordinates (`List[Tuple]` or `List[List[Tuple]]`, *optional*):
Answer coordinates of each table-question pair in the batch. The answer_coordinates must be a single
list of one or more tuples. Each tuple must be a (row_index, column_index) pair. The first data row
(not the column header row) has index 0. The first column has index 0.
answer_text (`List[str]` or `List[List[str]]`, *optional*):
Answer text of each table-question pair in the batch. The answer_text must be a single list of one or
more strings. Each string must be the answer text of a corresponding answer coordinate.
"""
if return_token_type_ids is not None and not add_special_tokens:
raise ValueError(
"Asking to return token_type_ids while setting add_special_tokens to False "
"results in an undefined behavior. Please set add_special_tokens to True or "
"set return_token_type_ids to None."
)
if (answer_coordinates and not answer_text) or (not answer_coordinates and answer_text):
raise ValueError("In case you provide answers, both answer_coordinates and answer_text should be provided")
if "is_split_into_words" in kwargs:
raise NotImplementedError("Currently TapasTokenizer only supports questions as strings.")
if return_offsets_mapping:
raise NotImplementedError(
"return_offset_mapping is not available when using Python tokenizers. "
"To use this feature, change your tokenizer to one deriving from "
"transformers.PreTrainedTokenizerFast."
)
return self._encode_plus(
table=table,
query=query,
answer_coordinates=answer_coordinates,
answer_text=answer_text,
add_special_tokens=add_special_tokens,
truncation=truncation,
padding=padding,
max_length=max_length,
pad_to_multiple_of=pad_to_multiple_of,
return_tensors=return_tensors,
return_token_type_ids=return_token_type_ids,
return_attention_mask=return_attention_mask,
return_special_tokens_mask=return_special_tokens_mask,
return_offsets_mapping=return_offsets_mapping,
return_length=return_length,
verbose=verbose,
**kwargs,
) | [
"def",
"encode_plus",
"(",
"self",
",",
"table",
":",
"\"pd.DataFrame\"",
",",
"query",
":",
"Optional",
"[",
"Union",
"[",
"TextInput",
",",
"PreTokenizedInput",
",",
"EncodedInput",
",",
"]",
"]",
"=",
"None",
",",
"answer_coordinates",
":",
"Optional",
"[... | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/tapas/tokenization_tapas.py#L927-L1008 | |
kanzure/nanoengineer | 874e4c9f8a9190f093625b267f9767e19f82e6c4 | cad/src/graphics/widgets/GLPane_text_and_color_methods.py | python | GLPane_text_and_color_methods._updateOriginAxisColor | (self) | return | [private]
Update the color of the origin axis to a shade that
will contrast well with the background. | [private]
Update the color of the origin axis to a shade that
will contrast well with the background. | [
"[",
"private",
"]",
"Update",
"the",
"color",
"of",
"the",
"origin",
"axis",
"to",
"a",
"shade",
"that",
"will",
"contrast",
"well",
"with",
"the",
"background",
"."
] | def _updateOriginAxisColor(self):
"""
[private]
Update the color of the origin axis to a shade that
will contrast well with the background.
"""
env.prefs.restore_defaults([originAxisColor_prefs_key])
axisColor = env.prefs[originAxisColor_prefs_key]
gradient = env.prefs[ backgroundGradient_prefs_key ]
if gradient == bgSOLID:
if not colors_differ_sufficiently(self.backgroundColor, axisColor):
env.prefs[originAxisColor_prefs_key] = ave_colors( 0.5, axisColor, white)
elif gradient == bgEVENING_SKY:
env.prefs[originAxisColor_prefs_key] = ave_colors( 0.9, axisColor, white)
return | [
"def",
"_updateOriginAxisColor",
"(",
"self",
")",
":",
"env",
".",
"prefs",
".",
"restore_defaults",
"(",
"[",
"originAxisColor_prefs_key",
"]",
")",
"axisColor",
"=",
"env",
".",
"prefs",
"[",
"originAxisColor_prefs_key",
"]",
"gradient",
"=",
"env",
".",
"p... | https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/graphics/widgets/GLPane_text_and_color_methods.py#L396-L411 | |
XX-net/XX-Net | a9898cfcf0084195fb7e69b6bc834e59aecdf14f | python3.8.2/Lib/pkg_resources/_vendor/pyparsing.py | python | traceParseAction | (f) | return z | Decorator for debugging parse actions.
When the parse action is called, this decorator will print C{">> entering I{method-name}(line:I{current_source_line}, I{parse_location}, I{matched_tokens})".}
When the parse action completes, the decorator will print C{"<<"} followed by the returned value, or any exception that the parse action raised.
Example::
wd = Word(alphas)
@traceParseAction
def remove_duplicate_chars(tokens):
return ''.join(sorted(set(''.join(tokens))))
wds = OneOrMore(wd).setParseAction(remove_duplicate_chars)
print(wds.parseString("slkdjs sld sldd sdlf sdljf"))
prints::
>>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))
<<leaving remove_duplicate_chars (ret: 'dfjkls')
['dfjkls'] | Decorator for debugging parse actions.
When the parse action is called, this decorator will print C{">> entering I{method-name}(line:I{current_source_line}, I{parse_location}, I{matched_tokens})".}
When the parse action completes, the decorator will print C{"<<"} followed by the returned value, or any exception that the parse action raised. | [
"Decorator",
"for",
"debugging",
"parse",
"actions",
".",
"When",
"the",
"parse",
"action",
"is",
"called",
"this",
"decorator",
"will",
"print",
"C",
"{",
">>",
"entering",
"I",
"{",
"method",
"-",
"name",
"}",
"(",
"line",
":",
"I",
"{",
"current_sourc... | def traceParseAction(f):
"""
Decorator for debugging parse actions.
When the parse action is called, this decorator will print C{">> entering I{method-name}(line:I{current_source_line}, I{parse_location}, I{matched_tokens})".}
When the parse action completes, the decorator will print C{"<<"} followed by the returned value, or any exception that the parse action raised.
Example::
wd = Word(alphas)
@traceParseAction
def remove_duplicate_chars(tokens):
return ''.join(sorted(set(''.join(tokens))))
wds = OneOrMore(wd).setParseAction(remove_duplicate_chars)
print(wds.parseString("slkdjs sld sldd sdlf sdljf"))
prints::
>>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))
<<leaving remove_duplicate_chars (ret: 'dfjkls')
['dfjkls']
"""
f = _trim_arity(f)
def z(*paArgs):
thisFunc = f.__name__
s,l,t = paArgs[-3:]
if len(paArgs)>3:
thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
sys.stderr.write( ">>entering %s(line: '%s', %d, %r)\n" % (thisFunc,line(l,s),l,t) )
try:
ret = f(*paArgs)
except Exception as exc:
sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) )
raise
sys.stderr.write( "<<leaving %s (ret: %r)\n" % (thisFunc,ret) )
return ret
try:
z.__name__ = f.__name__
except AttributeError:
pass
return z | [
"def",
"traceParseAction",
"(",
"f",
")",
":",
"f",
"=",
"_trim_arity",
"(",
"f",
")",
"def",
"z",
"(",
"*",
"paArgs",
")",
":",
"thisFunc",
"=",
"f",
".",
"__name__",
"s",
",",
"l",
",",
"t",
"=",
"paArgs",
"[",
"-",
"3",
":",
"]",
"if",
"le... | https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/pkg_resources/_vendor/pyparsing.py#L4406-L4445 | |
rockstor/rockstor-core | 81a0d5f5e0a6dfe5a922199828f66eeab0253e65 | src/rockstor/fs/btrfs.py | python | pool_usage | (mnt_pt) | return used / 1024 | Return used space of the storage pool mounted at mnt_pt.
Used space is considered to be:
- All space currently used by data;
- All space currently allocated for metadata and system data. | Return used space of the storage pool mounted at mnt_pt. | [
"Return",
"used",
"space",
"of",
"the",
"storage",
"pool",
"mounted",
"at",
"mnt_pt",
"."
] | def pool_usage(mnt_pt):
"""Return used space of the storage pool mounted at mnt_pt.
Used space is considered to be:
- All space currently used by data;
- All space currently allocated for metadata and system data.
"""
cmd = [BTRFS, "fi", "usage", "-b", mnt_pt]
out, err, rc = run_command(cmd)
used = 0
for line in out:
fields = re.split("\W+", line)
if line.startswith("Data"):
used += int(fields[5])
elif re.search("Size", line):
used += int(fields[3])
return used / 1024 | [
"def",
"pool_usage",
"(",
"mnt_pt",
")",
":",
"cmd",
"=",
"[",
"BTRFS",
",",
"\"fi\"",
",",
"\"usage\"",
",",
"\"-b\"",
",",
"mnt_pt",
"]",
"out",
",",
"err",
",",
"rc",
"=",
"run_command",
"(",
"cmd",
")",
"used",
"=",
"0",
"for",
"line",
"in",
... | https://github.com/rockstor/rockstor-core/blob/81a0d5f5e0a6dfe5a922199828f66eeab0253e65/src/rockstor/fs/btrfs.py#L1560-L1578 | |
HymanLiuTS/flaskTs | 286648286976e85d9b9a5873632331efcafe0b21 | flasky/lib/python2.7/site-packages/requests/adapters.py | python | HTTPAdapter.send | (self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None) | return self.build_response(request, resp) | Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param stream: (optional) Whether to stream the request content.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param verify: (optional) Whether to verify SSL certificates.
:param cert: (optional) Any user-provided SSL certificate to be trusted.
:param proxies: (optional) The proxies dictionary to apply to the request.
:rtype: requests.Response | Sends PreparedRequest object. Returns Response object. | [
"Sends",
"PreparedRequest",
"object",
".",
"Returns",
"Response",
"object",
"."
] | def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
"""Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param stream: (optional) Whether to stream the request content.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param verify: (optional) Whether to verify SSL certificates.
:param cert: (optional) Any user-provided SSL certificate to be trusted.
:param proxies: (optional) The proxies dictionary to apply to the request.
:rtype: requests.Response
"""
conn = self.get_connection(request.url, proxies)
self.cert_verify(conn, request.url, verify, cert)
url = self.request_url(request, proxies)
self.add_headers(request)
chunked = not (request.body is None or 'Content-Length' in request.headers)
if isinstance(timeout, tuple):
try:
connect, read = timeout
timeout = TimeoutSauce(connect=connect, read=read)
except ValueError as e:
# this may raise a string formatting error.
err = ("Invalid timeout {0}. Pass a (connect, read) "
"timeout tuple, or a single float to set "
"both timeouts to the same value".format(timeout))
raise ValueError(err)
else:
timeout = TimeoutSauce(connect=timeout, read=timeout)
try:
if not chunked:
resp = conn.urlopen(
method=request.method,
url=url,
body=request.body,
headers=request.headers,
redirect=False,
assert_same_host=False,
preload_content=False,
decode_content=False,
retries=self.max_retries,
timeout=timeout
)
# Send the request.
else:
if hasattr(conn, 'proxy_pool'):
conn = conn.proxy_pool
low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)
try:
low_conn.putrequest(request.method,
url,
skip_accept_encoding=True)
for header, value in request.headers.items():
low_conn.putheader(header, value)
low_conn.endheaders()
for i in request.body:
low_conn.send(hex(len(i))[2:].encode('utf-8'))
low_conn.send(b'\r\n')
low_conn.send(i)
low_conn.send(b'\r\n')
low_conn.send(b'0\r\n\r\n')
# Receive the response from the server
try:
# For Python 2.7+ versions, use buffering of HTTP
# responses
r = low_conn.getresponse(buffering=True)
except TypeError:
# For compatibility with Python 2.6 versions and back
r = low_conn.getresponse()
resp = HTTPResponse.from_httplib(
r,
pool=conn,
connection=low_conn,
preload_content=False,
decode_content=False
)
except:
# If we hit any problems here, clean up the connection.
# Then, reraise so that we can handle the actual exception.
low_conn.close()
raise
except (ProtocolError, socket.error) as err:
raise ConnectionError(err, request=request)
except MaxRetryError as e:
if isinstance(e.reason, ConnectTimeoutError):
# TODO: Remove this in 3.0.0: see #2811
if not isinstance(e.reason, NewConnectionError):
raise ConnectTimeout(e, request=request)
if isinstance(e.reason, ResponseError):
raise RetryError(e, request=request)
if isinstance(e.reason, _ProxyError):
raise ProxyError(e, request=request)
raise ConnectionError(e, request=request)
except ClosedPoolError as e:
raise ConnectionError(e, request=request)
except _ProxyError as e:
raise ProxyError(e)
except (_SSLError, _HTTPError) as e:
if isinstance(e, _SSLError):
raise SSLError(e, request=request)
elif isinstance(e, ReadTimeoutError):
raise ReadTimeout(e, request=request)
else:
raise
return self.build_response(request, resp) | [
"def",
"send",
"(",
"self",
",",
"request",
",",
"stream",
"=",
"False",
",",
"timeout",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
",",
"proxies",
"=",
"None",
")",
":",
"conn",
"=",
"self",
".",
"get_connection",
"(",
"req... | https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/requests/adapters.py#L375-L503 | |
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/schemes/elliptic_curves/heegner.py | python | kolyvagin_point | (self, D, c=ZZ(1), check=True) | return self.heegner_point(D,c,check=check).kolyvagin_point() | r"""
Return the Kolyvagin point on this curve associated to the
quadratic imaginary field `K=\QQ(\sqrt{D})` and conductor `c`.
INPUT:
- `D` -- a Heegner discriminant
- `c` -- (default: 1) conductor, must be coprime to `DN`
- ``check`` -- bool (default: ``True``)
OUTPUT:
The Kolyvagin point `P` of conductor `c`.
EXAMPLES::
sage: E = EllipticCurve('37a1')
sage: P = E.kolyvagin_point(-67); P
Kolyvagin point of discriminant -67 on elliptic curve of conductor 37
sage: P.numerical_approx() # abs tol 1e-14
(6.00000000000000 : -15.0000000000000 : 1.00000000000000)
sage: P.index()
6
sage: g = E((0,-1,1)) # a generator
sage: E.regulator() == E.regulator_of_points([g])
True
sage: 6*g
(6 : -15 : 1) | r"""
Return the Kolyvagin point on this curve associated to the
quadratic imaginary field `K=\QQ(\sqrt{D})` and conductor `c`. | [
"r",
"Return",
"the",
"Kolyvagin",
"point",
"on",
"this",
"curve",
"associated",
"to",
"the",
"quadratic",
"imaginary",
"field",
"K",
"=",
"\\",
"QQ",
"(",
"\\",
"sqrt",
"{",
"D",
"}",
")",
"and",
"conductor",
"c",
"."
] | def kolyvagin_point(self, D, c=ZZ(1), check=True):
r"""
Return the Kolyvagin point on this curve associated to the
quadratic imaginary field `K=\QQ(\sqrt{D})` and conductor `c`.
INPUT:
- `D` -- a Heegner discriminant
- `c` -- (default: 1) conductor, must be coprime to `DN`
- ``check`` -- bool (default: ``True``)
OUTPUT:
The Kolyvagin point `P` of conductor `c`.
EXAMPLES::
sage: E = EllipticCurve('37a1')
sage: P = E.kolyvagin_point(-67); P
Kolyvagin point of discriminant -67 on elliptic curve of conductor 37
sage: P.numerical_approx() # abs tol 1e-14
(6.00000000000000 : -15.0000000000000 : 1.00000000000000)
sage: P.index()
6
sage: g = E((0,-1,1)) # a generator
sage: E.regulator() == E.regulator_of_points([g])
True
sage: 6*g
(6 : -15 : 1)
"""
return self.heegner_point(D,c,check=check).kolyvagin_point() | [
"def",
"kolyvagin_point",
"(",
"self",
",",
"D",
",",
"c",
"=",
"ZZ",
"(",
"1",
")",
",",
"check",
"=",
"True",
")",
":",
"return",
"self",
".",
"heegner_point",
"(",
"D",
",",
"c",
",",
"check",
"=",
"check",
")",
".",
"kolyvagin_point",
"(",
")... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/schemes/elliptic_curves/heegner.py#L6395-L6429 | |
biermeester/Pylinter | 831f5cb6bb5860c135413a470276ea69bd31fef9 | pylinter.py | python | PylinterCommand.progress_tracker | (self, thread, i=0) | Display spinner while Pylint is running | Display spinner while Pylint is running | [
"Display",
"spinner",
"while",
"Pylint",
"is",
"running"
] | def progress_tracker(self, thread, i=0):
""" Display spinner while Pylint is running """
icons = [u"◐", u"◓", u"◑", u"◒"]
sublime.status_message("PyLinting %s" % icons[i])
if thread.is_alive():
i = (i + 1) % 4
sublime.set_timeout(lambda: self.progress_tracker(thread, i), 100)
else:
sublime.status_message("") | [
"def",
"progress_tracker",
"(",
"self",
",",
"thread",
",",
"i",
"=",
"0",
")",
":",
"icons",
"=",
"[",
"u\"◐\", ",
"u",
"◓\", u\"",
"◑",
", u\"◒\"",
"]",
"",
"",
"sublime",
".",
"status_message",
"(",
"\"PyLinting %s\"",
"%",
"icons",
"[",
"i",
"]",
... | https://github.com/biermeester/Pylinter/blob/831f5cb6bb5860c135413a470276ea69bd31fef9/pylinter.py#L375-L383 | ||
FreeOpcUa/python-opcua | 67f15551884d7f11659d52483e7b932999ca3a75 | opcua/common/node.py | python | Node.set_value | (self, value, varianttype=None) | Set value of a node. Only variables(properties) have values.
An exception will be generated for other node types.
value argument is either:
* a python built-in type, converted to opc-ua
optionnaly using the variantype argument.
* a ua.Variant, varianttype is then ignored
* a ua.DataValue, you then have full control over data send to server
WARNING: On server side, ref to object is directly saved in our UA db, if this is a mutable object
and you modfy it afterward, then the object in db will be modified without any
data change event generated | Set value of a node. Only variables(properties) have values.
An exception will be generated for other node types.
value argument is either:
* a python built-in type, converted to opc-ua
optionnaly using the variantype argument.
* a ua.Variant, varianttype is then ignored
* a ua.DataValue, you then have full control over data send to server
WARNING: On server side, ref to object is directly saved in our UA db, if this is a mutable object
and you modfy it afterward, then the object in db will be modified without any
data change event generated | [
"Set",
"value",
"of",
"a",
"node",
".",
"Only",
"variables",
"(",
"properties",
")",
"have",
"values",
".",
"An",
"exception",
"will",
"be",
"generated",
"for",
"other",
"node",
"types",
".",
"value",
"argument",
"is",
"either",
":",
"*",
"a",
"python",
... | def set_value(self, value, varianttype=None):
"""
Set value of a node. Only variables(properties) have values.
An exception will be generated for other node types.
value argument is either:
* a python built-in type, converted to opc-ua
optionnaly using the variantype argument.
* a ua.Variant, varianttype is then ignored
* a ua.DataValue, you then have full control over data send to server
WARNING: On server side, ref to object is directly saved in our UA db, if this is a mutable object
and you modfy it afterward, then the object in db will be modified without any
data change event generated
"""
datavalue = None
if isinstance(value, ua.DataValue):
datavalue = value
elif isinstance(value, ua.Variant):
datavalue = ua.DataValue(value)
datavalue.SourceTimestamp = datetime.utcnow()
else:
datavalue = ua.DataValue(ua.Variant(value, varianttype))
datavalue.SourceTimestamp = datetime.utcnow()
self.set_attribute(ua.AttributeIds.Value, datavalue) | [
"def",
"set_value",
"(",
"self",
",",
"value",
",",
"varianttype",
"=",
"None",
")",
":",
"datavalue",
"=",
"None",
"if",
"isinstance",
"(",
"value",
",",
"ua",
".",
"DataValue",
")",
":",
"datavalue",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
... | https://github.com/FreeOpcUa/python-opcua/blob/67f15551884d7f11659d52483e7b932999ca3a75/opcua/common/node.py#L195-L217 | ||
tbertinmahieux/MSongsDB | 0c276e289606d5bd6f3991f713e7e9b1d4384e44 | PythonSrc/DatasetCreation/dataset_filestats.py | python | die_with_usage | () | HELP MENU | HELP MENU | [
"HELP",
"MENU"
] | def die_with_usage():
""" HELP MENU """
print 'dataset_filestats.py'
print ' by T. Bertin-Mahieux (2010) Columbia University'
print ' tb2332@columbia.edu'
print 'Simple util to check the file repartition and the most'
print 'recent file in the Million Song dataset directory'
print 'usage:'
print ' python dataset_filestats.py <maindir>'
sys.exit(0) | [
"def",
"die_with_usage",
"(",
")",
":",
"print",
"'dataset_filestats.py'",
"print",
"' by T. Bertin-Mahieux (2010) Columbia University'",
"print",
"' tb2332@columbia.edu'",
"print",
"'Simple util to check the file repartition and the most'",
"print",
"'recent file in the Million S... | https://github.com/tbertinmahieux/MSongsDB/blob/0c276e289606d5bd6f3991f713e7e9b1d4384e44/PythonSrc/DatasetCreation/dataset_filestats.py#L102-L111 | ||
liuyuemaicha/Adversarial-Learning-for-Neural-Dialogue-Generation-in-Tensorflow | 2b54fe7fc72554aeb25e29c8022a573b9dec4d04 | utils/data_utils.py | python | basic_tokenizer | (sentence) | return [w for w in words if w] | Very basic tokenizer: split the sentence into a list of tokens. | Very basic tokenizer: split the sentence into a list of tokens. | [
"Very",
"basic",
"tokenizer",
":",
"split",
"the",
"sentence",
"into",
"a",
"list",
"of",
"tokens",
"."
] | def basic_tokenizer(sentence):
"""Very basic tokenizer: split the sentence into a list of tokens."""
words = []
for space_separated_fragment in sentence.strip().split():
words.extend(_WORD_SPLIT.split(space_separated_fragment))
return [w for w in words if w] | [
"def",
"basic_tokenizer",
"(",
"sentence",
")",
":",
"words",
"=",
"[",
"]",
"for",
"space_separated_fragment",
"in",
"sentence",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
":",
"words",
".",
"extend",
"(",
"_WORD_SPLIT",
".",
"split",
"(",
"space_s... | https://github.com/liuyuemaicha/Adversarial-Learning-for-Neural-Dialogue-Generation-in-Tensorflow/blob/2b54fe7fc72554aeb25e29c8022a573b9dec4d04/utils/data_utils.py#L106-L111 | |
antonylesuisse/qweb | 2d6964a3e5cae90414c4f873eb770591f569dfe0 | qweb_python/examples/blog/blog.py | python | BlogApp.blog | (self, req, arg, v) | [] | def blog(self, req, arg, v):
v['url']=qweb.QWebURL("/",req.PATH_INFO) | [
"def",
"blog",
"(",
"self",
",",
"req",
",",
"arg",
",",
"v",
")",
":",
"v",
"[",
"'url'",
"]",
"=",
"qweb",
".",
"QWebURL",
"(",
"\"/\"",
",",
"req",
".",
"PATH_INFO",
")"
] | https://github.com/antonylesuisse/qweb/blob/2d6964a3e5cae90414c4f873eb770591f569dfe0/qweb_python/examples/blog/blog.py#L76-L77 | ||||
haiwen/seahub | e92fcd44e3e46260597d8faa9347cb8222b8b10d | seahub/api2/endpoints/admin/shares.py | python | AdminShares.put | (self, request, repo, path, share_type) | return Response(share_info) | Update user/group share permission.
Permission checking:
1. admin user. | Update user/group share permission. | [
"Update",
"user",
"/",
"group",
"share",
"permission",
"."
] | def put(self, request, repo, path, share_type):
""" Update user/group share permission.
Permission checking:
1. admin user.
"""
# argument check
permission = request.data.get('permission', None)
if not permission or permission not in get_available_repo_perms():
permission = normalize_custom_permission_name(permission)
if not permission:
error_msg = 'permission invalid.'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
share_info = {}
share_info['repo_id'] = repo.repo_id
share_info['path'] = path
share_info['share_type'] = share_type
# current `request.user.username` is admin user,
# so need to identify the repo owner specifically.
repo_owner = seafile_api.get_repo_owner(repo.repo_id)
username = request.user.username
share_to = request.data.get('share_to', None)
if share_type == 'user':
email = share_to
if not email or not is_valid_username(email):
error_msg = 'email %s invalid.' % email
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
try:
User.objects.get(email=email)
except User.DoesNotExist:
error_msg = 'User %s not found.' % email
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
if not has_shared_to_user(repo.repo_id, path, email):
error_msg = 'Shared items not found'
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
try:
update_user_dir_permission(repo.repo_id, path, repo_owner, email, permission)
send_perm_audit_msg('modify-repo-perm', username, email,
repo.repo_id, path, permission)
except Exception as e:
logger.error(e)
error_msg = 'Internal Server Error'
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
share_info['user_email'] = email
share_info['user_name'] = email2nickname(email)
share_info['permission'] = PERMISSION_READ_WRITE if permission == PERMISSION_ADMIN else permission
share_info['is_admin'] = permission == PERMISSION_ADMIN
if share_type == 'group':
group_id = share_to
try:
group_id = int(group_id)
except ValueError:
error_msg = 'group_id %s invalid.' % group_id
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
group = ccnet_api.get_group(group_id)
if not group:
error_msg = 'Group %s not found' % group_id
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
if not has_shared_to_group(repo.repo_id, path, group_id):
error_msg = 'Shared items not found'
return api_error(status.HTTP_404_NOT_FOUND, error_msg)
try:
update_group_dir_permission(repo.repo_id, path, repo_owner, group_id, permission)
send_perm_audit_msg('modify-repo-perm', username, group_id,
repo.repo_id, path, permission)
except Exception as e:
logger.error(e)
error_msg = 'Internal Server Error'
return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)
share_info['group_id'] = group_id
share_info['group_name'] = group.group_name
share_info['permission'] = PERMISSION_READ_WRITE if permission == PERMISSION_ADMIN else permission
share_info['is_admin'] = permission == PERMISSION_ADMIN
return Response(share_info) | [
"def",
"put",
"(",
"self",
",",
"request",
",",
"repo",
",",
"path",
",",
"share_type",
")",
":",
"# argument check",
"permission",
"=",
"request",
".",
"data",
".",
"get",
"(",
"'permission'",
",",
"None",
")",
"if",
"not",
"permission",
"or",
"permissi... | https://github.com/haiwen/seahub/blob/e92fcd44e3e46260597d8faa9347cb8222b8b10d/seahub/api2/endpoints/admin/shares.py#L304-L392 | |
scikit-hep/awkward-0.x | dd885bef15814f588b58944d2505296df4aaae0e | awkward0/type.py | python | fromnumpy | (shape, dtype, masked=False) | [] | def fromnumpy(shape, dtype, masked=False):
if not isinstance(shape, tuple):
shape = (shape,)
if not isinstance(dtype, numpy.dtype):
dtype = numpy.dtype(dtype)
if masked:
return OptionType(fromnumpy(shape, dtype))
elif dtype.subdtype is not None:
dt, sh = dtype.subdtype
return fromnumpy(shape + sh, dt)
else:
return ArrayType(*(shape + (dtype,))) | [
"def",
"fromnumpy",
"(",
"shape",
",",
"dtype",
",",
"masked",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"shape",
",",
"tuple",
")",
":",
"shape",
"=",
"(",
"shape",
",",
")",
"if",
"not",
"isinstance",
"(",
"dtype",
",",
"numpy",
"."... | https://github.com/scikit-hep/awkward-0.x/blob/dd885bef15814f588b58944d2505296df4aaae0e/awkward0/type.py#L611-L623 | ||||
Xyntax/DirBrute | 84a54013f57a4588add9c2032c7c6c0902e6f504 | libs/requests/adapters.py | python | HTTPAdapter.close | (self) | Disposes of any internal state.
Currently, this just closes the PoolManager, which closes pooled
connections. | Disposes of any internal state. | [
"Disposes",
"of",
"any",
"internal",
"state",
"."
] | def close(self):
"""Disposes of any internal state.
Currently, this just closes the PoolManager, which closes pooled
connections.
"""
self.poolmanager.clear() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"poolmanager",
".",
"clear",
"(",
")"
] | https://github.com/Xyntax/DirBrute/blob/84a54013f57a4588add9c2032c7c6c0902e6f504/libs/requests/adapters.py#L255-L261 | ||
Chaffelson/nipyapi | d3b186fd701ce308c2812746d98af9120955e810 | nipyapi/nifi/models/processor_entity.py | python | ProcessorEntity.position | (self, position) | Sets the position of this ProcessorEntity.
The position of this component in the UI if applicable.
:param position: The position of this ProcessorEntity.
:type: PositionDTO | Sets the position of this ProcessorEntity.
The position of this component in the UI if applicable. | [
"Sets",
"the",
"position",
"of",
"this",
"ProcessorEntity",
".",
"The",
"position",
"of",
"this",
"component",
"in",
"the",
"UI",
"if",
"applicable",
"."
] | def position(self, position):
"""
Sets the position of this ProcessorEntity.
The position of this component in the UI if applicable.
:param position: The position of this ProcessorEntity.
:type: PositionDTO
"""
self._position = position | [
"def",
"position",
"(",
"self",
",",
"position",
")",
":",
"self",
".",
"_position",
"=",
"position"
] | https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/processor_entity.py#L182-L191 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/Python-2.7.9/Lib/plat-mac/aetypes.py | python | Property.__repr__ | (self) | [] | def __repr__(self):
if self.fr:
return "Property(%r, %r)" % (self.seld.type, self.fr)
else:
return "Property(%r)" % (self.seld.type,) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"if",
"self",
".",
"fr",
":",
"return",
"\"Property(%r, %r)\"",
"%",
"(",
"self",
".",
"seld",
".",
"type",
",",
"self",
".",
"fr",
")",
"else",
":",
"return",
"\"Property(%r)\"",
"%",
"(",
"self",
".",
"seld... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/plat-mac/aetypes.py#L442-L446 | ||||
XX-net/XX-Net | a9898cfcf0084195fb7e69b6bc834e59aecdf14f | python3.8.2/Lib/smtplib.py | python | SMTP.has_extn | (self, opt) | return opt.lower() in self.esmtp_features | Does the server support a given SMTP service extension? | Does the server support a given SMTP service extension? | [
"Does",
"the",
"server",
"support",
"a",
"given",
"SMTP",
"service",
"extension?"
] | def has_extn(self, opt):
"""Does the server support a given SMTP service extension?"""
return opt.lower() in self.esmtp_features | [
"def",
"has_extn",
"(",
"self",
",",
"opt",
")",
":",
"return",
"opt",
".",
"lower",
"(",
")",
"in",
"self",
".",
"esmtp_features"
] | https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/smtplib.py#L489-L491 | |
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/ceilometer/ceilometer/publisher/__init__.py | python | get_publisher | (url, namespace='ceilometer.publisher') | return loaded_driver.driver(parse_result) | Get publisher driver and load it.
:param URL: URL for the publisher
:param namespace: Namespace to use to look for drivers. | Get publisher driver and load it. | [
"Get",
"publisher",
"driver",
"and",
"load",
"it",
"."
] | def get_publisher(url, namespace='ceilometer.publisher'):
"""Get publisher driver and load it.
:param URL: URL for the publisher
:param namespace: Namespace to use to look for drivers.
"""
parse_result = urlparse.urlparse(url)
loaded_driver = driver.DriverManager(namespace, parse_result.scheme)
return loaded_driver.driver(parse_result) | [
"def",
"get_publisher",
"(",
"url",
",",
"namespace",
"=",
"'ceilometer.publisher'",
")",
":",
"parse_result",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"loaded_driver",
"=",
"driver",
".",
"DriverManager",
"(",
"namespace",
",",
"parse_result",
".",
... | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/ceilometer/ceilometer/publisher/__init__.py#L26-L34 | |
SteveDoyle2/pyNastran | eda651ac2d4883d95a34951f8a002ff94f642a1a | pyNastran/converters/tecplot/zone.py | python | Zone.get_xyz | (self) | return xyz | turns 2d points into 3d points | turns 2d points into 3d points | [
"turns",
"2d",
"points",
"into",
"3d",
"points"
] | def get_xyz(self) -> np.ndarray:
"""turns 2d points into 3d points"""
nnodes3d = self.xyz.shape[0]
nnodes2d = self.xy.shape[0]
if nnodes2d and nnodes3d:
raise RuntimeError('2d and 3d nodes is not supported')
elif nnodes2d:
npoints = self.xy.shape[0]
xyz = np.zeros((npoints, 3), dtype=self.xy.dtype)
xyz[:, :2] = self.xy
elif nnodes3d:
xyz = self.xyz
else: # pragma: no cover
raise RuntimeError('failed to find 2d/3d nodes')
return xyz | [
"def",
"get_xyz",
"(",
"self",
")",
"->",
"np",
".",
"ndarray",
":",
"nnodes3d",
"=",
"self",
".",
"xyz",
".",
"shape",
"[",
"0",
"]",
"nnodes2d",
"=",
"self",
".",
"xy",
".",
"shape",
"[",
"0",
"]",
"if",
"nnodes2d",
"and",
"nnodes3d",
":",
"rai... | https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/converters/tecplot/zone.py#L100-L114 | |
hans/glove.py | f79a9c406b61bdf095c7a93a3392c035a91f581a | glove.py | python | build_cooccur | (vocab, corpus, window_size=10, min_count=None) | Build a word co-occurrence list for the given corpus.
This function is a tuple generator, where each element (representing
a cooccurrence pair) is of the form
(i_main, i_context, cooccurrence)
where `i_main` is the ID of the main word in the cooccurrence and
`i_context` is the ID of the context word, and `cooccurrence` is the
`X_{ij}` cooccurrence value as described in Pennington et al.
(2014).
If `min_count` is not `None`, cooccurrence pairs where either word
occurs in the corpus fewer than `min_count` times are ignored. | Build a word co-occurrence list for the given corpus. | [
"Build",
"a",
"word",
"co",
"-",
"occurrence",
"list",
"for",
"the",
"given",
"corpus",
"."
] | def build_cooccur(vocab, corpus, window_size=10, min_count=None):
"""
Build a word co-occurrence list for the given corpus.
This function is a tuple generator, where each element (representing
a cooccurrence pair) is of the form
(i_main, i_context, cooccurrence)
where `i_main` is the ID of the main word in the cooccurrence and
`i_context` is the ID of the context word, and `cooccurrence` is the
`X_{ij}` cooccurrence value as described in Pennington et al.
(2014).
If `min_count` is not `None`, cooccurrence pairs where either word
occurs in the corpus fewer than `min_count` times are ignored.
"""
vocab_size = len(vocab)
id2word = dict((i, word) for word, (i, _) in vocab.iteritems())
# Collect cooccurrences internally as a sparse matrix for passable
# indexing speed; we'll convert into a list later
cooccurrences = sparse.lil_matrix((vocab_size, vocab_size),
dtype=np.float64)
for i, line in enumerate(corpus):
if i % 1000 == 0:
logger.info("Building cooccurrence matrix: on line %i", i)
tokens = line.strip().split()
token_ids = [vocab[word][0] for word in tokens]
for center_i, center_id in enumerate(token_ids):
# Collect all word IDs in left window of center word
context_ids = token_ids[max(0, center_i - window_size) : center_i]
contexts_len = len(context_ids)
for left_i, left_id in enumerate(context_ids):
# Distance from center word
distance = contexts_len - left_i
# Weight by inverse of distance between words
increment = 1.0 / float(distance)
# Build co-occurrence matrix symmetrically (pretend we
# are calculating right contexts as well)
cooccurrences[center_id, left_id] += increment
cooccurrences[left_id, center_id] += increment
# Now yield our tuple sequence (dig into the LiL-matrix internals to
# quickly iterate through all nonzero cells)
for i, (row, data) in enumerate(itertools.izip(cooccurrences.rows,
cooccurrences.data)):
if min_count is not None and vocab[id2word[i]][1] < min_count:
continue
for data_idx, j in enumerate(row):
if min_count is not None and vocab[id2word[j]][1] < min_count:
continue
yield i, j, data[data_idx] | [
"def",
"build_cooccur",
"(",
"vocab",
",",
"corpus",
",",
"window_size",
"=",
"10",
",",
"min_count",
"=",
"None",
")",
":",
"vocab_size",
"=",
"len",
"(",
"vocab",
")",
"id2word",
"=",
"dict",
"(",
"(",
"i",
",",
"word",
")",
"for",
"word",
",",
"... | https://github.com/hans/glove.py/blob/f79a9c406b61bdf095c7a93a3392c035a91f581a/glove.py#L121-L182 | ||
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/site-packages/openid/consumer/discover.py | python | OpenIDServiceEndpoint.getDisplayIdentifier | (self) | Return the display_identifier if set, else return the claimed_id. | Return the display_identifier if set, else return the claimed_id. | [
"Return",
"the",
"display_identifier",
"if",
"set",
"else",
"return",
"the",
"claimed_id",
"."
] | def getDisplayIdentifier(self):
"""Return the display_identifier if set, else return the claimed_id.
"""
if self.display_identifier is not None:
return self.display_identifier
if self.claimed_id is None:
return None
else:
return urlparse.urldefrag(self.claimed_id)[0] | [
"def",
"getDisplayIdentifier",
"(",
"self",
")",
":",
"if",
"self",
".",
"display_identifier",
"is",
"not",
"None",
":",
"return",
"self",
".",
"display_identifier",
"if",
"self",
".",
"claimed_id",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",... | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/openid/consumer/discover.py#L85-L93 | ||
IronLanguages/ironpython2 | 51fdedeeda15727717fb8268a805f71b06c0b9f1 | Src/StdLib/repackage/setuptools/pkg_resources/extern/__init__.py | python | VendorImporter.load_module | (self, fullname) | Iterate over the search path to locate and load fullname. | Iterate over the search path to locate and load fullname. | [
"Iterate",
"over",
"the",
"search",
"path",
"to",
"locate",
"and",
"load",
"fullname",
"."
] | def load_module(self, fullname):
"""
Iterate over the search path to locate and load fullname.
"""
root, base, target = fullname.partition(self.root_name + '.')
for prefix in self.search_path:
try:
extant = prefix + target
__import__(extant)
mod = sys.modules[extant]
sys.modules[fullname] = mod
# mysterious hack:
# Remove the reference to the extant package/module
# on later Python versions to cause relative imports
# in the vendor package to resolve the same modules
# as those going through this importer.
if prefix and sys.version_info > (3, 3):
del sys.modules[extant]
return mod
except ImportError:
pass
else:
raise ImportError(
"The '{target}' package is required; "
"normally this is bundled with this package so if you get "
"this warning, consult the packager of your "
"distribution.".format(**locals())
) | [
"def",
"load_module",
"(",
"self",
",",
"fullname",
")",
":",
"root",
",",
"base",
",",
"target",
"=",
"fullname",
".",
"partition",
"(",
"self",
".",
"root_name",
"+",
"'.'",
")",
"for",
"prefix",
"in",
"self",
".",
"search_path",
":",
"try",
":",
"... | https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/repackage/setuptools/pkg_resources/extern/__init__.py#L35-L62 | ||
tanghaibao/goatools | 647e9dd833695f688cd16c2f9ea18f1692e5c6bc | goatools/grouper/plotobj.py | python | PltGroupedGos._get_gos_upper | (self, ntpltgo1, max_upper, go2parentids) | return self._get_gosrcs_upper(goids_possible, max_upper, go2parentids) | Plot a GO DAG for the upper portion of a single Group of user GOs. | Plot a GO DAG for the upper portion of a single Group of user GOs. | [
"Plot",
"a",
"GO",
"DAG",
"for",
"the",
"upper",
"portion",
"of",
"a",
"single",
"Group",
"of",
"user",
"GOs",
"."
] | def _get_gos_upper(self, ntpltgo1, max_upper, go2parentids):
"""Plot a GO DAG for the upper portion of a single Group of user GOs."""
# Get GO IDs which are in the hdrgo path
goids_possible = ntpltgo1.gosubdag.go2obj.keys()
# Get upper GO IDs which have the most descendants
return self._get_gosrcs_upper(goids_possible, max_upper, go2parentids) | [
"def",
"_get_gos_upper",
"(",
"self",
",",
"ntpltgo1",
",",
"max_upper",
",",
"go2parentids",
")",
":",
"# Get GO IDs which are in the hdrgo path",
"goids_possible",
"=",
"ntpltgo1",
".",
"gosubdag",
".",
"go2obj",
".",
"keys",
"(",
")",
"# Get upper GO IDs which have... | https://github.com/tanghaibao/goatools/blob/647e9dd833695f688cd16c2f9ea18f1692e5c6bc/goatools/grouper/plotobj.py#L209-L214 | |
optuna/optuna | 2c44c1a405ba059efd53f4b9c8e849d20fb95c0a | optuna/integration/_lightgbm_tuner/optimize.py | python | _LightGBMBaseTuner.tune_min_data_in_leaf | (self) | [] | def tune_min_data_in_leaf(self) -> None:
param_name = "min_child_samples"
param_values = [5, 10, 25, 50, 100]
sampler = optuna.samplers.GridSampler({param_name: param_values})
self._tune_params([param_name], len(param_values), sampler, "min_data_in_leaf") | [
"def",
"tune_min_data_in_leaf",
"(",
"self",
")",
"->",
"None",
":",
"param_name",
"=",
"\"min_child_samples\"",
"param_values",
"=",
"[",
"5",
",",
"10",
",",
"25",
",",
"50",
",",
"100",
"]",
"sampler",
"=",
"optuna",
".",
"samplers",
".",
"GridSampler",... | https://github.com/optuna/optuna/blob/2c44c1a405ba059efd53f4b9c8e849d20fb95c0a/optuna/integration/_lightgbm_tuner/optimize.py#L606-L611 | ||||
golismero/golismero | 7d605b937e241f51c1ca4f47b20f755eeefb9d76 | tools/sqlmap/thirdparty/bottle/bottle.py | python | cookie_is_encoded | (data) | return bool(data.startswith(tob('!')) and tob('?') in data) | Return True if the argument looks like a encoded cookie. | Return True if the argument looks like a encoded cookie. | [
"Return",
"True",
"if",
"the",
"argument",
"looks",
"like",
"a",
"encoded",
"cookie",
"."
] | def cookie_is_encoded(data):
''' Return True if the argument looks like a encoded cookie.'''
return bool(data.startswith(tob('!')) and tob('?') in data) | [
"def",
"cookie_is_encoded",
"(",
"data",
")",
":",
"return",
"bool",
"(",
"data",
".",
"startswith",
"(",
"tob",
"(",
"'!'",
")",
")",
"and",
"tob",
"(",
"'?'",
")",
"in",
"data",
")"
] | https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/tools/sqlmap/thirdparty/bottle/bottle.py#L2213-L2215 | |
EventGhost/EventGhost | 177be516849e74970d2e13cda82244be09f277ce | lib27/site-packages/tornado/platform/interface.py | python | Waker.close | (self) | Closes the waker's file descriptor(s). | Closes the waker's file descriptor(s). | [
"Closes",
"the",
"waker",
"s",
"file",
"descriptor",
"(",
"s",
")",
"."
] | def close(self):
"""Closes the waker's file descriptor(s)."""
raise NotImplementedError() | [
"def",
"close",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
")"
] | https://github.com/EventGhost/EventGhost/blob/177be516849e74970d2e13cda82244be09f277ce/lib27/site-packages/tornado/platform/interface.py#L61-L63 | ||
robertkrimen/gist-it | e4e67336df783ae4626fc73805a1fd52bc299012 | pyl/jinja2/runtime.py | python | Context.super | (self, name, current) | return BlockReference(name, self, blocks, index) | Render a parent block. | Render a parent block. | [
"Render",
"a",
"parent",
"block",
"."
] | def super(self, name, current):
"""Render a parent block."""
try:
blocks = self.blocks[name]
index = blocks.index(current) + 1
blocks[index]
except LookupError:
return self.environment.undefined('there is no parent block '
'called %r.' % name,
name='super')
return BlockReference(name, self, blocks, index) | [
"def",
"super",
"(",
"self",
",",
"name",
",",
"current",
")",
":",
"try",
":",
"blocks",
"=",
"self",
".",
"blocks",
"[",
"name",
"]",
"index",
"=",
"blocks",
".",
"index",
"(",
"current",
")",
"+",
"1",
"blocks",
"[",
"index",
"]",
"except",
"L... | https://github.com/robertkrimen/gist-it/blob/e4e67336df783ae4626fc73805a1fd52bc299012/pyl/jinja2/runtime.py#L122-L132 | |
llSourcell/AI_Artist | 3038c06c2e389b9c919c881c9a169efe2fd7810e | lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py | python | OrderedDict.itervalues | (self) | od.itervalues -> an iterator over the values in od | od.itervalues -> an iterator over the values in od | [
"od",
".",
"itervalues",
"-",
">",
"an",
"iterator",
"over",
"the",
"values",
"in",
"od"
] | def itervalues(self):
'od.itervalues -> an iterator over the values in od'
for k in self:
yield self[k] | [
"def",
"itervalues",
"(",
"self",
")",
":",
"for",
"k",
"in",
"self",
":",
"yield",
"self",
"[",
"k",
"]"
] | https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py#L132-L135 | ||
open-mmlab/mmpose | 0376d51efdd93b3c8f3338211130753fed808bb9 | mmpose/core/visualization/effects.py | python | apply_sunglasses_effect | (img,
pose_results,
sunglasses_img,
left_eye_index,
right_eye_index,
kpt_thr=0.5) | return img | Apply sunglasses effect.
Args:
img (np.ndarray): Image data.
pose_results (list[dict]): The pose estimation results containing:
- "keypoints" ([K,3]): keypoint detection result in [x, y, score]
sunglasses_img (np.ndarray): Sunglasses image with white background.
left_eye_index (int): Keypoint index of left eye
right_eye_index (int): Keypoint index of right eye
kpt_thr (float): The score threshold of required keypoints. | Apply sunglasses effect. | [
"Apply",
"sunglasses",
"effect",
"."
] | def apply_sunglasses_effect(img,
pose_results,
sunglasses_img,
left_eye_index,
right_eye_index,
kpt_thr=0.5):
"""Apply sunglasses effect.
Args:
img (np.ndarray): Image data.
pose_results (list[dict]): The pose estimation results containing:
- "keypoints" ([K,3]): keypoint detection result in [x, y, score]
sunglasses_img (np.ndarray): Sunglasses image with white background.
left_eye_index (int): Keypoint index of left eye
right_eye_index (int): Keypoint index of right eye
kpt_thr (float): The score threshold of required keypoints.
"""
hm, wm = sunglasses_img.shape[:2]
# anchor points in the sunglasses mask
pts_src = np.array([[0.3 * wm, 0.3 * hm], [0.3 * wm, 0.7 * hm],
[0.7 * wm, 0.3 * hm], [0.7 * wm, 0.7 * hm]],
dtype=np.float32)
for pose in pose_results:
kpts = pose['keypoints']
if kpts[left_eye_index, 2] < kpt_thr or kpts[right_eye_index,
2] < kpt_thr:
continue
kpt_leye = kpts[left_eye_index, :2]
kpt_reye = kpts[right_eye_index, :2]
# orthogonal vector to the left-to-right eyes
vo = 0.5 * (kpt_reye - kpt_leye)[::-1] * [-1, 1]
# anchor points in the image by eye positions
pts_tar = np.vstack(
[kpt_reye + vo, kpt_reye - vo, kpt_leye + vo, kpt_leye - vo])
h_mat, _ = cv2.findHomography(pts_src, pts_tar)
patch = cv2.warpPerspective(
sunglasses_img,
h_mat,
dsize=(img.shape[1], img.shape[0]),
borderValue=(255, 255, 255))
# mask the white background area in the patch with a threshold 200
mask = cv2.cvtColor(patch, cv2.COLOR_BGR2GRAY)
mask = (mask < 200).astype(np.uint8)
img = cv2.copyTo(patch, mask, img)
return img | [
"def",
"apply_sunglasses_effect",
"(",
"img",
",",
"pose_results",
",",
"sunglasses_img",
",",
"left_eye_index",
",",
"right_eye_index",
",",
"kpt_thr",
"=",
"0.5",
")",
":",
"hm",
",",
"wm",
"=",
"sunglasses_img",
".",
"shape",
"[",
":",
"2",
"]",
"# anchor... | https://github.com/open-mmlab/mmpose/blob/0376d51efdd93b3c8f3338211130753fed808bb9/mmpose/core/visualization/effects.py#L60-L111 | |
dropbox/dropbox-sdk-python | 015437429be224732990041164a21a0501235db1 | dropbox/team_log.py | python | AdminAlertGeneralStateEnum.is_active | (self) | return self._tag == 'active' | Check if the union tag is ``active``.
:rtype: bool | Check if the union tag is ``active``. | [
"Check",
"if",
"the",
"union",
"tag",
"is",
"active",
"."
] | def is_active(self):
"""
Check if the union tag is ``active``.
:rtype: bool
"""
return self._tag == 'active' | [
"def",
"is_active",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tag",
"==",
"'active'"
] | https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L1192-L1198 | |
NuID/nebulousAD | 37a44f131d13f1668a73b61f2444ad93b9e657cc | nebulousAD/modimpacket/dot11.py | python | Dot11ManagementAssociationRequest.get_listen_interval | (self) | return b | Return the 802.11 Management Association Request Frame \'Listen Interval\' field. | Return the 802.11 Management Association Request Frame \'Listen Interval\' field. | [
"Return",
"the",
"802",
".",
"11",
"Management",
"Association",
"Request",
"Frame",
"\\",
"Listen",
"Interval",
"\\",
"field",
"."
] | def get_listen_interval(self):
'Return the 802.11 Management Association Request Frame \'Listen Interval\' field. '
b = self.header.get_word(2, "<")
return b | [
"def",
"get_listen_interval",
"(",
"self",
")",
":",
"b",
"=",
"self",
".",
"header",
".",
"get_word",
"(",
"2",
",",
"\"<\"",
")",
"return",
"b"
] | https://github.com/NuID/nebulousAD/blob/37a44f131d13f1668a73b61f2444ad93b9e657cc/nebulousAD/modimpacket/dot11.py#L2763-L2766 | |
robotframework/RIDE | 6e8a50774ff33dead3a2757a11b0b4418ab205c0 | src/robotide/lib/robot/libraries/String.py | python | String.replace_string_using_regexp | (self, string, pattern, replace_with, count=-1) | return re.sub(pattern, replace_with, string, max(count, 0)) | Replaces ``pattern`` in the given ``string`` with ``replace_with``.
This keyword is otherwise identical to `Replace String`, but
the ``pattern`` to search for is considered to be a regular
expression. See `BuiltIn.Should Match Regexp` for more
information about Python regular expression syntax in general
and how to use it in Robot Framework test data in particular.
If you need to just remove a string see `Remove String Using Regexp`.
Examples:
| ${str} = | Replace String Using Regexp | ${str} | 20\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\d | <DATE> |
| ${str} = | Replace String Using Regexp | ${str} | (Hello|Hi) | ${EMPTY} | count=1 | | Replaces ``pattern`` in the given ``string`` with ``replace_with``. | [
"Replaces",
"pattern",
"in",
"the",
"given",
"string",
"with",
"replace_with",
"."
] | def replace_string_using_regexp(self, string, pattern, replace_with, count=-1):
"""Replaces ``pattern`` in the given ``string`` with ``replace_with``.
This keyword is otherwise identical to `Replace String`, but
the ``pattern`` to search for is considered to be a regular
expression. See `BuiltIn.Should Match Regexp` for more
information about Python regular expression syntax in general
and how to use it in Robot Framework test data in particular.
If you need to just remove a string see `Remove String Using Regexp`.
Examples:
| ${str} = | Replace String Using Regexp | ${str} | 20\\\\d\\\\d-\\\\d\\\\d-\\\\d\\\\d | <DATE> |
| ${str} = | Replace String Using Regexp | ${str} | (Hello|Hi) | ${EMPTY} | count=1 |
"""
count = self._convert_to_integer(count, 'count')
# re.sub handles 0 and negative counts differently than string.replace
if count == 0:
return string
return re.sub(pattern, replace_with, string, max(count, 0)) | [
"def",
"replace_string_using_regexp",
"(",
"self",
",",
"string",
",",
"pattern",
",",
"replace_with",
",",
"count",
"=",
"-",
"1",
")",
":",
"count",
"=",
"self",
".",
"_convert_to_integer",
"(",
"count",
",",
"'count'",
")",
"# re.sub handles 0 and negative co... | https://github.com/robotframework/RIDE/blob/6e8a50774ff33dead3a2757a11b0b4418ab205c0/src/robotide/lib/robot/libraries/String.py#L383-L402 | |
postlund/pyatv | 4ed1f5539f37d86d80272663d1f2ea34a6c41ec4 | pyatv/core/facade.py | python | FacadePower.turn_on | (self, await_new_state: bool = False) | Turn device on. | Turn device on. | [
"Turn",
"device",
"on",
"."
] | async def turn_on(self, await_new_state: bool = False) -> None:
"""Turn device on."""
await self.relay("turn_on", priority=self.OVERRIDE_PRIORITIES)(
await_new_state=await_new_state
) | [
"async",
"def",
"turn_on",
"(",
"self",
",",
"await_new_state",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"await",
"self",
".",
"relay",
"(",
"\"turn_on\"",
",",
"priority",
"=",
"self",
".",
"OVERRIDE_PRIORITIES",
")",
"(",
"await_new_state",
"="... | https://github.com/postlund/pyatv/blob/4ed1f5539f37d86d80272663d1f2ea34a6c41ec4/pyatv/core/facade.py#L341-L345 | ||
partho-maple/coding-interview-gym | f9b28916da31935a27900794cfb8b91be3b38b9b | leetcode.com/python/84_Largest_Rectangle_in_Histogram.py | python | Solution.largestRectangleArea | (self, heights) | return finalArea | :type heights: List[int]
:rtype: int | :type heights: List[int]
:rtype: int | [
":",
"type",
"heights",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] | def largestRectangleArea(self, heights):
"""
:type heights: List[int]
:rtype: int
"""
heights.append(0)
stack = [-1]
finalArea = 0
for i in range(len(heights)):
while heights[i] < heights[stack[-1]]:
height = heights[stack.pop()]
width = i - stack[-1] - 1
finalArea = max(finalArea, height*width)
stack.append(i)
heights.pop()
return finalArea | [
"def",
"largestRectangleArea",
"(",
"self",
",",
"heights",
")",
":",
"heights",
".",
"append",
"(",
"0",
")",
"stack",
"=",
"[",
"-",
"1",
"]",
"finalArea",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"heights",
")",
")",
":",
"while",
... | https://github.com/partho-maple/coding-interview-gym/blob/f9b28916da31935a27900794cfb8b91be3b38b9b/leetcode.com/python/84_Largest_Rectangle_in_Histogram.py#L4-L19 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/src/ansible/oc_adm_registry.py | python | main | () | ansible oc module for registry | ansible oc module for registry | [
"ansible",
"oc",
"module",
"for",
"registry"
] | def main():
'''
ansible oc module for registry
'''
module = AnsibleModule(
argument_spec=dict(
state=dict(default='present', type='str',
choices=['present', 'absent']),
debug=dict(default=False, type='bool'),
namespace=dict(default='default', type='str'),
name=dict(default=None, required=True, type='str'),
kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
images=dict(default=None, type='str'),
latest_images=dict(default=False, type='bool'),
labels=dict(default=None, type='dict'),
ports=dict(default=['5000'], type='list'),
replicas=dict(default=1, type='int'),
selector=dict(default=None, type='str'),
service_account=dict(default='registry', type='str'),
mount_host=dict(default=None, type='str'),
volume_mounts=dict(default=None, type='list'),
env_vars=dict(default={}, type='dict'),
edits=dict(default=[], type='list'),
enforce_quota=dict(default=False, type='bool'),
force=dict(default=False, type='bool'),
daemonset=dict(default=False, type='bool'),
tls_key=dict(default=None, type='str'),
tls_certificate=dict(default=None, type='str'),
),
supports_check_mode=True,
)
results = Registry.run_ansible(module.params, module.check_mode)
if 'failed' in results:
module.fail_json(**results)
module.exit_json(**results) | [
"def",
"main",
"(",
")",
":",
"module",
"=",
"AnsibleModule",
"(",
"argument_spec",
"=",
"dict",
"(",
"state",
"=",
"dict",
"(",
"default",
"=",
"'present'",
",",
"type",
"=",
"'str'",
",",
"choices",
"=",
"[",
"'present'",
",",
"'absent'",
"]",
")",
... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/src/ansible/oc_adm_registry.py#L4-L43 | ||
idapython/src | 839d93ac969bc1a152982464907445bc0d18a1f8 | pywraps/py_kernwin_plgform.py | python | PluginForm.Close | (self, options) | return _ida_kernwin.plgform_close(self.__clink__, options) | Closes the form.
@param options: Close options (WCLS_SAVE, WCLS_NO_CONTEXT, ...)
@return: None | Closes the form. | [
"Closes",
"the",
"form",
"."
] | def Close(self, options):
"""
Closes the form.
@param options: Close options (WCLS_SAVE, WCLS_NO_CONTEXT, ...)
@return: None
"""
return _ida_kernwin.plgform_close(self.__clink__, options) | [
"def",
"Close",
"(",
"self",
",",
"options",
")",
":",
"return",
"_ida_kernwin",
".",
"plgform_close",
"(",
"self",
".",
"__clink__",
",",
"options",
")"
] | https://github.com/idapython/src/blob/839d93ac969bc1a152982464907445bc0d18a1f8/pywraps/py_kernwin_plgform.py#L168-L176 | |
bradleyfay/py-Goldsberry | 4406c8a066f5c4e41b7e722b4d4e598379bb82f0 | goldsberry/draft/_Draft.py | python | non_stationary_shooting.data | (self) | return [dict(zip(_headers, value)) for value in _values] | Returns list of dicts with anthropometric data
For best results, wrap this in pandas.DataFrame()
Return values:
PLAYER_ID --
TEMP_PLAYER_ID --
PLAYER_NAME --
FIRST_NAME --
LAST_NAME --
POSITION -- Projected Position of the Prospect
OFF_DRIB_COLLEGE_BREAK_LEFT_MADE --
OFF_DRIB_COLLEGE_BREAK_LEFT_ATTEMPT --
OFF_DRIB_COLLEGE_BREAK_LEFT_PCT -- Off Dribble College Break Left - A player takes six
shots coming off the dribble from the left break area of the court. The shot is from
about the distance of a college three pointer (20 ft. 9 in.).
OFF_DRIB_COLLEGE_BREAK_RIGHT_MADE --
OFF_DRIB_COLLEGE_BREAK_RIGHT_ATTEMPT --
OFF_DRIB_COLLEGE_BREAK_RIGHT_PCT -- Off Dribble College Break Right - A player takes six
shots coming off the dribble from the right break area of the court. The shot is from
about the distance of a college three pointer (20 ft. 9 in.).
OFF_DRIB_COLLEGE_TOP_KEY_MADE --
OFF_DRIB_COLLEGE_TOP_KEY_ATTEMPT --
OFF_DRIB_COLLEGE_TOP_KEY_PCT -- Off Dribble College Top Key - A player takes six shots
coming off the dribble from the top of the key. The shot is from about the distance
of a college three pointer (20 ft. 9 in.).
OFF_DRIB_FIFTEEN_BREAK_LEFT_MADE --
OFF_DRIB_FIFTEEN_BREAK_LEFT_ATTEMPT --
OFF_DRIB_FIFTEEN_BREAK_LEFT_PCT -- Off Dribble Fifteen Break Left - A player takes six
shots coming off the dribble from 15 feet away from the basket on the left break
area of the court.
OFF_DRIB_FIFTEEN_BREAK_RIGHT_MADE --
OFF_DRIB_FIFTEEN_BREAK_RIGHT_ATTEMPT --
OFF_DRIB_FIFTEEN_BREAK_RIGHT_PCT -- Off Dribble Fifteen Break Right - A player takes six
shots coming off the dribble from 15 feet away from the basket on the right break area
of the court.
OFF_DRIB_FIFTEEN_TOP_KEY_MADE --
OFF_DRIB_FIFTEEN_TOP_KEY_ATTEMPT --
OFF_DRIB_FIFTEEN_TOP_KEY_PCT -- Off Dribble Fifteen Top Key - A player takes six shots
coming off the dribble from 15 feet out at the top of the key.
ON_MOVE_COLLEGE_MADE --
ON_MOVE_COLLEGE_ATTEMPT --
ON_MOVE_COLLEGE_PCT -- On the Move College - 35 seconds to attempt as many shots as time
allows from college 3-pt range (20 ft. 9 in.) while moving between spots (corners
and elbows from both sides).
ON_MOVE_FIFTEEN_MADE --
ON_MOVE_FIFTEEN_ATTEMPT --
ON_MOVE_FIFTEEN_PCT -- On the Move Fifteen - 35 seconds to attempt as many shots as time
allows from 15 feet while moving between spots (corners and elbows from both sides). | Returns list of dicts with anthropometric data | [
"Returns",
"list",
"of",
"dicts",
"with",
"anthropometric",
"data"
] | def data(self):
"""Returns list of dicts with anthropometric data
For best results, wrap this in pandas.DataFrame()
Return values:
PLAYER_ID --
TEMP_PLAYER_ID --
PLAYER_NAME --
FIRST_NAME --
LAST_NAME --
POSITION -- Projected Position of the Prospect
OFF_DRIB_COLLEGE_BREAK_LEFT_MADE --
OFF_DRIB_COLLEGE_BREAK_LEFT_ATTEMPT --
OFF_DRIB_COLLEGE_BREAK_LEFT_PCT -- Off Dribble College Break Left - A player takes six
shots coming off the dribble from the left break area of the court. The shot is from
about the distance of a college three pointer (20 ft. 9 in.).
OFF_DRIB_COLLEGE_BREAK_RIGHT_MADE --
OFF_DRIB_COLLEGE_BREAK_RIGHT_ATTEMPT --
OFF_DRIB_COLLEGE_BREAK_RIGHT_PCT -- Off Dribble College Break Right - A player takes six
shots coming off the dribble from the right break area of the court. The shot is from
about the distance of a college three pointer (20 ft. 9 in.).
OFF_DRIB_COLLEGE_TOP_KEY_MADE --
OFF_DRIB_COLLEGE_TOP_KEY_ATTEMPT --
OFF_DRIB_COLLEGE_TOP_KEY_PCT -- Off Dribble College Top Key - A player takes six shots
coming off the dribble from the top of the key. The shot is from about the distance
of a college three pointer (20 ft. 9 in.).
OFF_DRIB_FIFTEEN_BREAK_LEFT_MADE --
OFF_DRIB_FIFTEEN_BREAK_LEFT_ATTEMPT --
OFF_DRIB_FIFTEEN_BREAK_LEFT_PCT -- Off Dribble Fifteen Break Left - A player takes six
shots coming off the dribble from 15 feet away from the basket on the left break
area of the court.
OFF_DRIB_FIFTEEN_BREAK_RIGHT_MADE --
OFF_DRIB_FIFTEEN_BREAK_RIGHT_ATTEMPT --
OFF_DRIB_FIFTEEN_BREAK_RIGHT_PCT -- Off Dribble Fifteen Break Right - A player takes six
shots coming off the dribble from 15 feet away from the basket on the right break area
of the court.
OFF_DRIB_FIFTEEN_TOP_KEY_MADE --
OFF_DRIB_FIFTEEN_TOP_KEY_ATTEMPT --
OFF_DRIB_FIFTEEN_TOP_KEY_PCT -- Off Dribble Fifteen Top Key - A player takes six shots
coming off the dribble from 15 feet out at the top of the key.
ON_MOVE_COLLEGE_MADE --
ON_MOVE_COLLEGE_ATTEMPT --
ON_MOVE_COLLEGE_PCT -- On the Move College - 35 seconds to attempt as many shots as time
allows from college 3-pt range (20 ft. 9 in.) while moving between spots (corners
and elbows from both sides).
ON_MOVE_FIFTEEN_MADE --
ON_MOVE_FIFTEEN_ATTEMPT --
ON_MOVE_FIFTEEN_PCT -- On the Move Fifteen - 35 seconds to attempt as many shots as time
allows from 15 feet while moving between spots (corners and elbows from both sides).
"""
_headers = self._pull.json()['resultSets'][0]['headers']
_values = self._pull.json()['resultSets'][0]['rowSet']
return [dict(zip(_headers, value)) for value in _values] | [
"def",
"data",
"(",
"self",
")",
":",
"_headers",
"=",
"self",
".",
"_pull",
".",
"json",
"(",
")",
"[",
"'resultSets'",
"]",
"[",
"0",
"]",
"[",
"'headers'",
"]",
"_values",
"=",
"self",
".",
"_pull",
".",
"json",
"(",
")",
"[",
"'resultSets'",
... | https://github.com/bradleyfay/py-Goldsberry/blob/4406c8a066f5c4e41b7e722b4d4e598379bb82f0/goldsberry/draft/_Draft.py#L90-L143 | |
barseghyanartur/django-dash | dc00513b65e017c40f278a0a7df2a18ec8da9bc3 | examples/example/settings/helpers.py | python | project_dir | (base) | return os.path.abspath(
os.path.join(os.path.dirname(__file__), base).replace('\\', '/')
) | Project dir. | Project dir. | [
"Project",
"dir",
"."
] | def project_dir(base):
"""Project dir."""
return os.path.abspath(
os.path.join(os.path.dirname(__file__), base).replace('\\', '/')
) | [
"def",
"project_dir",
"(",
"base",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"base",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/... | https://github.com/barseghyanartur/django-dash/blob/dc00513b65e017c40f278a0a7df2a18ec8da9bc3/examples/example/settings/helpers.py#L10-L14 | |
microsoft/azure-devops-python-api | 451cade4c475482792cbe9e522c1fee32393139e | azure-devops/azure/devops/v6_0/project_analysis/project_analysis_client.py | python | ProjectAnalysisClient.get_git_repositories_activity_metrics | (self, project, from_date, aggregation_type, skip, top) | return self._deserialize('[RepositoryActivityMetrics]', self._unwrap_collection(response)) | GetGitRepositoriesActivityMetrics.
[Preview API] Retrieves git activity metrics for repositories matching a specified criteria.
:param str project: Project ID or project name
:param datetime from_date: Date from which, the trends are to be fetched.
:param str aggregation_type: Bucket size on which, trends are to be aggregated.
:param int skip: The number of repositories to ignore.
:param int top: The number of repositories for which activity metrics are to be retrieved.
:rtype: [RepositoryActivityMetrics] | GetGitRepositoriesActivityMetrics.
[Preview API] Retrieves git activity metrics for repositories matching a specified criteria.
:param str project: Project ID or project name
:param datetime from_date: Date from which, the trends are to be fetched.
:param str aggregation_type: Bucket size on which, trends are to be aggregated.
:param int skip: The number of repositories to ignore.
:param int top: The number of repositories for which activity metrics are to be retrieved.
:rtype: [RepositoryActivityMetrics] | [
"GetGitRepositoriesActivityMetrics",
".",
"[",
"Preview",
"API",
"]",
"Retrieves",
"git",
"activity",
"metrics",
"for",
"repositories",
"matching",
"a",
"specified",
"criteria",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
... | def get_git_repositories_activity_metrics(self, project, from_date, aggregation_type, skip, top):
"""GetGitRepositoriesActivityMetrics.
[Preview API] Retrieves git activity metrics for repositories matching a specified criteria.
:param str project: Project ID or project name
:param datetime from_date: Date from which, the trends are to be fetched.
:param str aggregation_type: Bucket size on which, trends are to be aggregated.
:param int skip: The number of repositories to ignore.
:param int top: The number of repositories for which activity metrics are to be retrieved.
:rtype: [RepositoryActivityMetrics]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if from_date is not None:
query_parameters['fromDate'] = self._serialize.query('from_date', from_date, 'iso-8601')
if aggregation_type is not None:
query_parameters['aggregationType'] = self._serialize.query('aggregation_type', aggregation_type, 'str')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
response = self._send(http_method='GET',
location_id='df7fbbca-630a-40e3-8aa3-7a3faf66947e',
version='6.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[RepositoryActivityMetrics]', self._unwrap_collection(response)) | [
"def",
"get_git_repositories_activity_metrics",
"(",
"self",
",",
"project",
",",
"from_date",
",",
"aggregation_type",
",",
"skip",
",",
"top",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'... | https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v6_0/project_analysis/project_analysis_client.py#L66-L93 | |
tp4a/teleport | 1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad | server/www/packages/packages-linux/x64/PIL/ImageOps.py | python | exif_transpose | (image) | return image.copy() | If an image has an EXIF Orientation tag, return a new image that is
transposed accordingly. Otherwise, return a copy of the image.
:param image: The image to transpose.
:return: An image. | If an image has an EXIF Orientation tag, return a new image that is
transposed accordingly. Otherwise, return a copy of the image. | [
"If",
"an",
"image",
"has",
"an",
"EXIF",
"Orientation",
"tag",
"return",
"a",
"new",
"image",
"that",
"is",
"transposed",
"accordingly",
".",
"Otherwise",
"return",
"a",
"copy",
"of",
"the",
"image",
"."
] | def exif_transpose(image):
"""
If an image has an EXIF Orientation tag, return a new image that is
transposed accordingly. Otherwise, return a copy of the image.
:param image: The image to transpose.
:return: An image.
"""
exif = image.getexif()
orientation = exif.get(0x0112)
method = {
2: Image.FLIP_LEFT_RIGHT,
3: Image.ROTATE_180,
4: Image.FLIP_TOP_BOTTOM,
5: Image.TRANSPOSE,
6: Image.ROTATE_270,
7: Image.TRANSVERSE,
8: Image.ROTATE_90,
}.get(orientation)
if method is not None:
transposed_image = image.transpose(method)
del exif[0x0112]
transposed_image.info["exif"] = exif.tobytes()
return transposed_image
return image.copy() | [
"def",
"exif_transpose",
"(",
"image",
")",
":",
"exif",
"=",
"image",
".",
"getexif",
"(",
")",
"orientation",
"=",
"exif",
".",
"get",
"(",
"0x0112",
")",
"method",
"=",
"{",
"2",
":",
"Image",
".",
"FLIP_LEFT_RIGHT",
",",
"3",
":",
"Image",
".",
... | https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-linux/x64/PIL/ImageOps.py#L527-L551 | |
9miao/G-Firefly | 8fbeeb3ef9782600560be48228c91cfb8f5ff87d | gfirefly/gfirefly/distributed/node.py | python | BilateralClientProtocol.__init__ | (self, transport, factory) | [] | def __init__(self, transport, factory):
rpc.PBClientProtocl.__init__(self, transport, factory) | [
"def",
"__init__",
"(",
"self",
",",
"transport",
",",
"factory",
")",
":",
"rpc",
".",
"PBClientProtocl",
".",
"__init__",
"(",
"self",
",",
"transport",
",",
"factory",
")"
] | https://github.com/9miao/G-Firefly/blob/8fbeeb3ef9782600560be48228c91cfb8f5ff87d/gfirefly/gfirefly/distributed/node.py#L15-L16 | ||||
fabioz/PyDev.Debugger | 0f8c02a010fe5690405da1dd30ed72326191ce63 | pydevd_attach_to_process/winappdbg/breakpoint.py | python | _BreakpointContainer.dont_hook_function | (self, pid, address) | Removes a function hook set by L{hook_function}.
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved. | Removes a function hook set by L{hook_function}. | [
"Removes",
"a",
"function",
"hook",
"set",
"by",
"L",
"{",
"hook_function",
"}",
"."
] | def dont_hook_function(self, pid, address):
"""
Removes a function hook set by L{hook_function}.
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
"""
self.dont_break_at(pid, address) | [
"def",
"dont_hook_function",
"(",
"self",
",",
"pid",
",",
"address",
")",
":",
"self",
".",
"dont_break_at",
"(",
"pid",
",",
"address",
")"
] | https://github.com/fabioz/PyDev.Debugger/blob/0f8c02a010fe5690405da1dd30ed72326191ce63/pydevd_attach_to_process/winappdbg/breakpoint.py#L4136-L4149 | ||
JDAI-CV/fast-reid | 31d99b793fe0937461b9c9bc8a8a11f88bf5642c | fastreid/utils/events.py | python | JSONWriter.write | (self) | [] | def write(self):
storage = get_event_storage()
to_save = defaultdict(dict)
for k, (v, iter) in storage.latest_with_smoothing_hint(self._window_size).items():
# keep scalars that have not been written
if iter <= self._last_write:
continue
to_save[iter][k] = v
if len(to_save):
all_iters = sorted(to_save.keys())
self._last_write = max(all_iters)
for itr, scalars_per_iter in to_save.items():
scalars_per_iter["iteration"] = itr
self._file_handle.write(json.dumps(scalars_per_iter, sort_keys=True) + "\n")
self._file_handle.flush()
try:
os.fsync(self._file_handle.fileno())
except AttributeError:
pass | [
"def",
"write",
"(",
"self",
")",
":",
"storage",
"=",
"get_event_storage",
"(",
")",
"to_save",
"=",
"defaultdict",
"(",
"dict",
")",
"for",
"k",
",",
"(",
"v",
",",
"iter",
")",
"in",
"storage",
".",
"latest_with_smoothing_hint",
"(",
"self",
".",
"_... | https://github.com/JDAI-CV/fast-reid/blob/31d99b793fe0937461b9c9bc8a8a11f88bf5642c/fastreid/utils/events.py#L99-L119 | ||||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/plat-sunos5/STROPTS.py | python | RESTORE_GLOBALS | (RP) | return | [] | def RESTORE_GLOBALS(RP): return | [
"def",
"RESTORE_GLOBALS",
"(",
"RP",
")",
":",
"return"
] | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/plat-sunos5/STROPTS.py#L715-L715 | |||
sagemath/sage | f9b2db94f675ff16963ccdefba4f1a3393b3fe0d | src/sage/misc/benchmark.py | python | bench7 | () | return (desc, cputime(t)) | Run a benchmark.
BENCHMARK::
sage: from sage.misc.benchmark import *
sage: print(bench7()[0])
Compute the Mordell-Weil group of y^2 = x^3 + 37*x - 997. | Run a benchmark. | [
"Run",
"a",
"benchmark",
"."
] | def bench7():
"""
Run a benchmark.
BENCHMARK::
sage: from sage.misc.benchmark import *
sage: print(bench7()[0])
Compute the Mordell-Weil group of y^2 = x^3 + 37*x - 997.
"""
desc = """Compute the Mordell-Weil group of y^2 = x^3 + 37*x - 997."""
E = EllipticCurve([0,0,0,37,-997])
t = cputime()
G = E.gens()
return (desc, cputime(t)) | [
"def",
"bench7",
"(",
")",
":",
"desc",
"=",
"\"\"\"Compute the Mordell-Weil group of y^2 = x^3 + 37*x - 997.\"\"\"",
"E",
"=",
"EllipticCurve",
"(",
"[",
"0",
",",
"0",
",",
"0",
",",
"37",
",",
"-",
"997",
"]",
")",
"t",
"=",
"cputime",
"(",
")",
"G",
... | https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/misc/benchmark.py#L204-L219 | |
sfu-db/dataprep | 6dfb9c659e8bf73f07978ae195d0372495c6f118 | dataprep/clean/clean_eu_eic.py | python | _format | (val: Any, output_format: str = "standard", errors: str = "coarse") | return result | Reformat a number string with proper separators and whitespace.
Parameters
----------
val
The value of number string.
output_format
If output_format = 'compact', return string without any separators or whitespace.
If output_format = 'standard', return string with proper separators and whitespace.
Note: in the case of EIC, the compact format is the same as the standard one. | Reformat a number string with proper separators and whitespace. | [
"Reformat",
"a",
"number",
"string",
"with",
"proper",
"separators",
"and",
"whitespace",
"."
] | def _format(val: Any, output_format: str = "standard", errors: str = "coarse") -> Any:
"""
Reformat a number string with proper separators and whitespace.
Parameters
----------
val
The value of number string.
output_format
If output_format = 'compact', return string without any separators or whitespace.
If output_format = 'standard', return string with proper separators and whitespace.
Note: in the case of EIC, the compact format is the same as the standard one.
"""
val = str(val)
result: Any = []
if val in NULL_VALUES:
return [np.nan]
if not validate_eu_eic(val):
if errors == "raise":
raise ValueError(f"Unable to parse value {val}")
error_result = val if errors == "ignore" else np.nan
return [error_result]
if output_format in {"compact", "standard"}:
result = [eic.compact(val)] + result
return result | [
"def",
"_format",
"(",
"val",
":",
"Any",
",",
"output_format",
":",
"str",
"=",
"\"standard\"",
",",
"errors",
":",
"str",
"=",
"\"coarse\"",
")",
"->",
"Any",
":",
"val",
"=",
"str",
"(",
"val",
")",
"result",
":",
"Any",
"=",
"[",
"]",
"if",
"... | https://github.com/sfu-db/dataprep/blob/6dfb9c659e8bf73f07978ae195d0372495c6f118/dataprep/clean/clean_eu_eic.py#L133-L161 | |
callmeray/PointMVSNet | cacb2d719bac4f8ed63f9cdd9d6e91b01c991077 | pointmvsnet/functions/functions.py | python | construct_edge_feature_index | (feature, knn_inds) | return edge_feature | Construct edge feature for each point (or regarded as a node)
using advanced indexing
Args:
feature (torch.Tensor): point features, (batch_size, channels, num_nodes),
knn_inds (torch.Tensor): indices of k-nearest neighbour, (batch_size, num_nodes, k)
Returns:
edge_feature: (batch_size, 2*channels, num_nodes, k) | Construct edge feature for each point (or regarded as a node)
using advanced indexing | [
"Construct",
"edge",
"feature",
"for",
"each",
"point",
"(",
"or",
"regarded",
"as",
"a",
"node",
")",
"using",
"advanced",
"indexing"
] | def construct_edge_feature_index(feature, knn_inds):
"""Construct edge feature for each point (or regarded as a node)
using advanced indexing
Args:
feature (torch.Tensor): point features, (batch_size, channels, num_nodes),
knn_inds (torch.Tensor): indices of k-nearest neighbour, (batch_size, num_nodes, k)
Returns:
edge_feature: (batch_size, 2*channels, num_nodes, k)
"""
batch_size, channels, num_nodes = feature.shape
k = knn_inds.size(-1)
feature_central = feature.unsqueeze(3).expand(batch_size, channels, num_nodes, k)
batch_idx = torch.arange(batch_size).view(-1, 1, 1, 1)
feature_idx = torch.arange(channels).view(1, -1, 1, 1)
# (batch_size, channels, num_nodes, k)
feature_neighbour = feature[batch_idx, feature_idx, knn_inds.unsqueeze(1)]
edge_feature = torch.cat((feature_central, feature_neighbour - feature_central), 1)
return edge_feature | [
"def",
"construct_edge_feature_index",
"(",
"feature",
",",
"knn_inds",
")",
":",
"batch_size",
",",
"channels",
",",
"num_nodes",
"=",
"feature",
".",
"shape",
"k",
"=",
"knn_inds",
".",
"size",
"(",
"-",
"1",
")",
"feature_central",
"=",
"feature",
".",
... | https://github.com/callmeray/PointMVSNet/blob/cacb2d719bac4f8ed63f9cdd9d6e91b01c991077/pointmvsnet/functions/functions.py#L29-L51 | |
inspurer/WorkAttendanceSystem | 1221e2d67bdf5bb15fe99517cc3ded58ccb066df | V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/distlib/database.py | python | DistributionPath.get_file_path | (self, name, relative_path) | return dist.get_resource_path(relative_path) | Return the path to a resource file. | Return the path to a resource file. | [
"Return",
"the",
"path",
"to",
"a",
"resource",
"file",
"."
] | def get_file_path(self, name, relative_path):
"""
Return the path to a resource file.
"""
dist = self.get_distribution(name)
if dist is None:
raise LookupError('no distribution named %r found' % name)
return dist.get_resource_path(relative_path) | [
"def",
"get_file_path",
"(",
"self",
",",
"name",
",",
"relative_path",
")",
":",
"dist",
"=",
"self",
".",
"get_distribution",
"(",
"name",
")",
"if",
"dist",
"is",
"None",
":",
"raise",
"LookupError",
"(",
"'no distribution named %r found'",
"%",
"name",
"... | https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/distlib/database.py#L281-L288 | |
caiiiac/Machine-Learning-with-Python | 1a26c4467da41ca4ebc3d5bd789ea942ef79422f | MachineLearning/venv/lib/python3.5/site-packages/pandas/compat/numpy/function.py | python | validate_resampler_func | (method, args, kwargs) | 'args' and 'kwargs' should be empty because all of
their necessary parameters are explicitly listed in
the function signature | 'args' and 'kwargs' should be empty because all of
their necessary parameters are explicitly listed in
the function signature | [
"args",
"and",
"kwargs",
"should",
"be",
"empty",
"because",
"all",
"of",
"their",
"necessary",
"parameters",
"are",
"explicitly",
"listed",
"in",
"the",
"function",
"signature"
] | def validate_resampler_func(method, args, kwargs):
"""
'args' and 'kwargs' should be empty because all of
their necessary parameters are explicitly listed in
the function signature
"""
if len(args) + len(kwargs) > 0:
if method in RESAMPLER_NUMPY_OPS:
raise UnsupportedFunctionCall((
"numpy operations are not valid "
"with resample. Use .resample(...)."
"{func}() instead".format(func=method)))
else:
raise TypeError("too many arguments passed in") | [
"def",
"validate_resampler_func",
"(",
"method",
",",
"args",
",",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"+",
"len",
"(",
"kwargs",
")",
">",
"0",
":",
"if",
"method",
"in",
"RESAMPLER_NUMPY_OPS",
":",
"raise",
"UnsupportedFunctionCall",
"(",
... | https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pandas/compat/numpy/function.py#L333-L346 | ||
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/lib-python/3/xml/etree/ElementTree.py | python | XMLID | (text, parser=None) | return tree, ids | [] | def XMLID(text, parser=None):
if not parser:
parser = XMLParser(target=TreeBuilder())
parser.feed(text)
tree = parser.close()
ids = {}
for elem in tree.iter():
id = elem.get("id")
if id:
ids[id] = elem
return tree, ids | [
"def",
"XMLID",
"(",
"text",
",",
"parser",
"=",
"None",
")",
":",
"if",
"not",
"parser",
":",
"parser",
"=",
"XMLParser",
"(",
"target",
"=",
"TreeBuilder",
"(",
")",
")",
"parser",
".",
"feed",
"(",
"text",
")",
"tree",
"=",
"parser",
".",
"close... | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/xml/etree/ElementTree.py#L1350-L1360 | |||
mozillazg/pypy | 2ff5cd960c075c991389f842c6d59e71cf0cb7d0 | lib-python/2.7/logging/__init__.py | python | warning | (msg, *args, **kwargs) | Log a message with severity 'WARNING' on the root logger. | Log a message with severity 'WARNING' on the root logger. | [
"Log",
"a",
"message",
"with",
"severity",
"WARNING",
"on",
"the",
"root",
"logger",
"."
] | def warning(msg, *args, **kwargs):
"""
Log a message with severity 'WARNING' on the root logger.
"""
if len(root.handlers) == 0:
basicConfig()
root.warning(msg, *args, **kwargs) | [
"def",
"warning",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"root",
".",
"handlers",
")",
"==",
"0",
":",
"basicConfig",
"(",
")",
"root",
".",
"warning",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"... | https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/logging/__init__.py#L1633-L1639 | ||
jabbalaci/Bash-Utils | c6fb115834a221c4aaba8eaa37f650beea45ef29 | lib/firefox.py | python | open_url_in_curr_tab | (url) | Open a URL in the *current* tab. | Open a URL in the *current* tab. | [
"Open",
"a",
"URL",
"in",
"the",
"*",
"current",
"*",
"tab",
"."
] | def open_url_in_curr_tab(url):
"""
Open a URL in the *current* tab.
"""
with Mozrepl() as mr:
cmd = "content.location.href = '{url}'".format(url=url)
mr.cmd(cmd) | [
"def",
"open_url_in_curr_tab",
"(",
"url",
")",
":",
"with",
"Mozrepl",
"(",
")",
"as",
"mr",
":",
"cmd",
"=",
"\"content.location.href = '{url}'\"",
".",
"format",
"(",
"url",
"=",
"url",
")",
"mr",
".",
"cmd",
"(",
"cmd",
")"
] | https://github.com/jabbalaci/Bash-Utils/blob/c6fb115834a221c4aaba8eaa37f650beea45ef29/lib/firefox.py#L80-L86 | ||
deeptools/deepTools | ac42d29c298c026aa0c53c9db2553087ebc86b97 | deeptools/plotFingerprint.py | python | getSyntheticJSD | (vec) | return getJSDcommon(chip, input) | This is largely similar to getJSD, with the 'input' sample being a Poisson distribution with lambda the average coverage in the IP bins | This is largely similar to getJSD, with the 'input' sample being a Poisson distribution with lambda the average coverage in the IP bins | [
"This",
"is",
"largely",
"similar",
"to",
"getJSD",
"with",
"the",
"input",
"sample",
"being",
"a",
"Poisson",
"distribution",
"with",
"lambda",
"the",
"average",
"coverage",
"in",
"the",
"IP",
"bins"
] | def getSyntheticJSD(vec):
"""
This is largely similar to getJSD, with the 'input' sample being a Poisson distribution with lambda the average coverage in the IP bins
"""
lamb = np.mean(vec) # Average coverage
coverage = np.sum(vec)
chip = np.zeros(MAXLEN, dtype=np.int)
for val in vec:
# N.B., we need to clip past the end of the array
if val >= MAXLEN:
val = MAXLEN - 1
# This effectively removes differences due to coverage percentages
if val > 0:
chip[int(val)] += 1
input = coverage * poisson.pmf(np.arange(1, MAXLEN), lamb)
if chip[-1] > 0:
print("{} bins had coverage over the maximum value of {} during synthetic JSD computation".format(chip[-1], MAXLEN))
return getJSDcommon(chip, input) | [
"def",
"getSyntheticJSD",
"(",
"vec",
")",
":",
"lamb",
"=",
"np",
".",
"mean",
"(",
"vec",
")",
"# Average coverage",
"coverage",
"=",
"np",
".",
"sum",
"(",
"vec",
")",
"chip",
"=",
"np",
".",
"zeros",
"(",
"MAXLEN",
",",
"dtype",
"=",
"np",
".",... | https://github.com/deeptools/deepTools/blob/ac42d29c298c026aa0c53c9db2553087ebc86b97/deeptools/plotFingerprint.py#L236-L255 | |
yilifzf/BDCI_Car_2018 | cc1b0193213ed77f3403ee663ec210056f883888 | bert/run_classifier_ensemble_polarity.py | python | SstProcessor.get_test_examples | (self, data_dir) | return self._create_examples(
self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") | See base class. | See base class. | [
"See",
"base",
"class",
"."
] | def get_test_examples(self, data_dir):
"""See base class."""
return self._create_examples(
self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") | [
"def",
"get_test_examples",
"(",
"self",
",",
"data_dir",
")",
":",
"return",
"self",
".",
"_create_examples",
"(",
"self",
".",
"_read_tsv",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"\"test.tsv\"",
")",
")",
",",
"\"test\"",
")"
] | https://github.com/yilifzf/BDCI_Car_2018/blob/cc1b0193213ed77f3403ee663ec210056f883888/bert/run_classifier_ensemble_polarity.py#L187-L190 | |
DataDog/integrations-core | 934674b29d94b70ccc008f76ea172d0cdae05e1e | http_check/datadog_checks/http_check/config_models/defaults.py | python | instance_tls_ca_cert | (field, value) | return get_default_field_value(field, value) | [] | def instance_tls_ca_cert(field, value):
return get_default_field_value(field, value) | [
"def",
"instance_tls_ca_cert",
"(",
"field",
",",
"value",
")",
":",
"return",
"get_default_field_value",
"(",
"field",
",",
"value",
")"
] | https://github.com/DataDog/integrations-core/blob/934674b29d94b70ccc008f76ea172d0cdae05e1e/http_check/datadog_checks/http_check/config_models/defaults.py#L213-L214 | |||
ppengtang/pcl.pytorch | 4e0280e5e1470f705e620eda26f881d627c5016c | lib/utils/boxes.py | python | clip_tiled_boxes | (boxes, im_shape) | return boxes | Clip boxes to image boundaries. im_shape is [height, width] and boxes
has shape (N, 4 * num_tiled_boxes). | Clip boxes to image boundaries. im_shape is [height, width] and boxes
has shape (N, 4 * num_tiled_boxes). | [
"Clip",
"boxes",
"to",
"image",
"boundaries",
".",
"im_shape",
"is",
"[",
"height",
"width",
"]",
"and",
"boxes",
"has",
"shape",
"(",
"N",
"4",
"*",
"num_tiled_boxes",
")",
"."
] | def clip_tiled_boxes(boxes, im_shape):
"""Clip boxes to image boundaries. im_shape is [height, width] and boxes
has shape (N, 4 * num_tiled_boxes)."""
assert boxes.shape[1] % 4 == 0, \
'boxes.shape[1] is {:d}, but must be divisible by 4.'.format(
boxes.shape[1]
)
# x1 >= 0
boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0)
# y1 >= 0
boxes[:, 1::4] = np.maximum(np.minimum(boxes[:, 1::4], im_shape[0] - 1), 0)
# x2 < im_shape[1]
boxes[:, 2::4] = np.maximum(np.minimum(boxes[:, 2::4], im_shape[1] - 1), 0)
# y2 < im_shape[0]
boxes[:, 3::4] = np.maximum(np.minimum(boxes[:, 3::4], im_shape[0] - 1), 0)
return boxes | [
"def",
"clip_tiled_boxes",
"(",
"boxes",
",",
"im_shape",
")",
":",
"assert",
"boxes",
".",
"shape",
"[",
"1",
"]",
"%",
"4",
"==",
"0",
",",
"'boxes.shape[1] is {:d}, but must be divisible by 4.'",
".",
"format",
"(",
"boxes",
".",
"shape",
"[",
"1",
"]",
... | https://github.com/ppengtang/pcl.pytorch/blob/4e0280e5e1470f705e620eda26f881d627c5016c/lib/utils/boxes.py#L139-L154 | |
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/ecm/v20190719/models.py | python | DescribeSubnetsResponse.__init__ | (self) | r"""
:param TotalCount: 符合条件的实例数量。
:type TotalCount: int
:param SubnetSet: 子网对象。
注意:此字段可能返回 null,表示取不到有效值。
:type SubnetSet: list of Subnet
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | r"""
:param TotalCount: 符合条件的实例数量。
:type TotalCount: int
:param SubnetSet: 子网对象。
注意:此字段可能返回 null,表示取不到有效值。
:type SubnetSet: list of Subnet
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | [
"r",
":",
"param",
"TotalCount",
":",
"符合条件的实例数量。",
":",
"type",
"TotalCount",
":",
"int",
":",
"param",
"SubnetSet",
":",
"子网对象。",
"注意:此字段可能返回",
"null,表示取不到有效值。",
":",
"type",
"SubnetSet",
":",
"list",
"of",
"Subnet",
":",
"param",
"RequestId",
":",
"唯一请求",... | def __init__(self):
r"""
:param TotalCount: 符合条件的实例数量。
:type TotalCount: int
:param SubnetSet: 子网对象。
注意:此字段可能返回 null,表示取不到有效值。
:type SubnetSet: list of Subnet
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.SubnetSet = None
self.RequestId = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"TotalCount",
"=",
"None",
"self",
".",
"SubnetSet",
"=",
"None",
"self",
".",
"RequestId",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/ecm/v20190719/models.py#L4825-L4837 | ||
pytroll/satpy | 09e51f932048f98cce7919a4ff8bd2ec01e1ae98 | satpy/readers/__init__.py | python | _assign_files_to_readers | (files_to_sort, reader_names,
reader_kwargs) | return reader_dict | Assign files to readers.
Given a list of file names (paths), match those to reader instances.
Internal helper for group_files.
Args:
files_to_sort (Collection[str]): Files to assign to readers.
reader_names (Collection[str]): Readers to consider
reader_kwargs (Mapping):
Returns:
Mapping[str, Tuple[reader, Set[str]]]
Mapping where the keys are reader names and the values are tuples of
(reader_configs, filenames). | Assign files to readers. | [
"Assign",
"files",
"to",
"readers",
"."
] | def _assign_files_to_readers(files_to_sort, reader_names,
reader_kwargs):
"""Assign files to readers.
Given a list of file names (paths), match those to reader instances.
Internal helper for group_files.
Args:
files_to_sort (Collection[str]): Files to assign to readers.
reader_names (Collection[str]): Readers to consider
reader_kwargs (Mapping):
Returns:
Mapping[str, Tuple[reader, Set[str]]]
Mapping where the keys are reader names and the values are tuples of
(reader_configs, filenames).
"""
files_to_sort = set(files_to_sort)
reader_dict = {}
for reader_configs in configs_for_reader(reader_names):
try:
reader = load_reader(reader_configs, **reader_kwargs)
except yaml.constructor.ConstructorError:
LOG.exception(
f"ConstructorError loading {reader_configs!s}, "
"probably a missing dependency, skipping "
"corresponding reader (if you did not explicitly "
"specify the reader, Satpy tries all; performance "
"will improve if you pass readers explicitly).")
continue
reader_name = reader.info["name"]
files_matching = set(reader.filter_selected_filenames(files_to_sort))
files_to_sort -= files_matching
if files_matching or reader_names is not None:
reader_dict[reader_name] = (reader, files_matching)
if files_to_sort:
raise ValueError("No matching readers found for these files: " +
", ".join(files_to_sort))
return reader_dict | [
"def",
"_assign_files_to_readers",
"(",
"files_to_sort",
",",
"reader_names",
",",
"reader_kwargs",
")",
":",
"files_to_sort",
"=",
"set",
"(",
"files_to_sort",
")",
"reader_dict",
"=",
"{",
"}",
"for",
"reader_configs",
"in",
"configs_for_reader",
"(",
"reader_name... | https://github.com/pytroll/satpy/blob/09e51f932048f98cce7919a4ff8bd2ec01e1ae98/satpy/readers/__init__.py#L118-L157 | |
deanishe/alfred-pwgen | 7966df5c5e05f2fca5b9406fb2a6116f7030608a | src/workflow/workflow.py | python | Workflow.cache_serializer | (self, serializer_name) | Set the default cache serialization format.
.. versionadded:: 1.8
This serializer is used by :meth:`cache_data()` and
:meth:`cached_data()`
The specified serializer must already by registered with the
:class:`SerializerManager` at `~workflow.workflow.manager`,
otherwise a :class:`ValueError` will be raised.
:param serializer_name: Name of default serializer to use.
:type serializer_name: | Set the default cache serialization format. | [
"Set",
"the",
"default",
"cache",
"serialization",
"format",
"."
] | def cache_serializer(self, serializer_name):
"""Set the default cache serialization format.
.. versionadded:: 1.8
This serializer is used by :meth:`cache_data()` and
:meth:`cached_data()`
The specified serializer must already by registered with the
:class:`SerializerManager` at `~workflow.workflow.manager`,
otherwise a :class:`ValueError` will be raised.
:param serializer_name: Name of default serializer to use.
:type serializer_name:
"""
if manager.serializer(serializer_name) is None:
raise ValueError(
'Unknown serializer : `{0}`. Register your serializer '
'with `manager` first.'.format(serializer_name))
self.logger.debug('default cache serializer: %s', serializer_name)
self._cache_serializer = serializer_name | [
"def",
"cache_serializer",
"(",
"self",
",",
"serializer_name",
")",
":",
"if",
"manager",
".",
"serializer",
"(",
"serializer_name",
")",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Unknown serializer : `{0}`. Register your serializer '",
"'with `manager` first.'",
... | https://github.com/deanishe/alfred-pwgen/blob/7966df5c5e05f2fca5b9406fb2a6116f7030608a/src/workflow/workflow.py#L1491-L1514 | ||
xuanzebi/BERT-CH-NER | 24bf95411e831281ffc6c13f3ea9382870a17d64 | bert-master/tf_metrics.py | python | pr_re_fbeta | (cm, pos_indices, beta=1) | return pr, re, fbeta | Uses a confusion matrix to compute precision, recall and fbeta | Uses a confusion matrix to compute precision, recall and fbeta | [
"Uses",
"a",
"confusion",
"matrix",
"to",
"compute",
"precision",
"recall",
"and",
"fbeta"
] | def pr_re_fbeta(cm, pos_indices, beta=1):
"""Uses a confusion matrix to compute precision, recall and fbeta"""
num_classes = cm.shape[0]
neg_indices = [i for i in range(num_classes) if i not in pos_indices]
cm_mask = np.ones([num_classes, num_classes])
cm_mask[neg_indices, neg_indices] = 0
diag_sum = tf.reduce_sum(tf.diag_part(cm * cm_mask))
cm_mask = np.ones([num_classes, num_classes])
cm_mask[:, neg_indices] = 0
tot_pred = tf.reduce_sum(cm * cm_mask)
cm_mask = np.ones([num_classes, num_classes])
cm_mask[neg_indices, :] = 0
tot_gold = tf.reduce_sum(cm * cm_mask)
pr = safe_div(diag_sum, tot_pred)
re = safe_div(diag_sum, tot_gold)
fbeta = safe_div((1. + beta**2) * pr * re, beta**2 * pr + re)
return pr, re, fbeta | [
"def",
"pr_re_fbeta",
"(",
"cm",
",",
"pos_indices",
",",
"beta",
"=",
"1",
")",
":",
"num_classes",
"=",
"cm",
".",
"shape",
"[",
"0",
"]",
"neg_indices",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"num_classes",
")",
"if",
"i",
"not",
"in",
... | https://github.com/xuanzebi/BERT-CH-NER/blob/24bf95411e831281ffc6c13f3ea9382870a17d64/bert-master/tf_metrics.py#L145-L165 | |
bendmorris/static-python | 2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473 | Lib/mailbox.py | python | Mailbox.values | (self) | return list(self.itervalues()) | Return a list of messages. Memory intensive. | Return a list of messages. Memory intensive. | [
"Return",
"a",
"list",
"of",
"messages",
".",
"Memory",
"intensive",
"."
] | def values(self):
"""Return a list of messages. Memory intensive."""
return list(self.itervalues()) | [
"def",
"values",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"itervalues",
"(",
")",
")"
] | https://github.com/bendmorris/static-python/blob/2e0f8c4d7ed5b359dc7d8a75b6fb37e6b6c5c473/Lib/mailbox.py#L119-L121 | |
emesene/emesene | 4548a4098310e21b16437bb36223a7f632a4f7bc | emesene/e3/papylib/papyon/papyon/client.py | python | Client.call_manager | (self) | return self._call_manager | The SIP call manager
@type: L{SIPCallManager<papyon.sip.SIPCallManager>} | The SIP call manager | [
"The",
"SIP",
"call",
"manager"
] | def call_manager(self):
"""The SIP call manager
@type: L{SIPCallManager<papyon.sip.SIPCallManager>}"""
return self._call_manager | [
"def",
"call_manager",
"(",
"self",
")",
":",
"return",
"self",
".",
"_call_manager"
] | https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/e3/papylib/papyon/papyon/client.py#L217-L220 | |
securesystemslab/zippy | ff0e84ac99442c2c55fe1d285332cfd4e185e089 | zippy/benchmarks/src/benchmarks/sympy/sympy/core/expr.py | python | Expr.__rmul__ | (self, other) | return Mul(other, self) | [] | def __rmul__(self, other):
return Mul(other, self) | [
"def",
"__rmul__",
"(",
"self",
",",
"other",
")",
":",
"return",
"Mul",
"(",
"other",
",",
"self",
")"
] | https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/core/expr.py#L131-L132 | |||
GNS3/gns3-server | aff06572d4173df945ad29ea8feb274f7885d9e4 | gns3server/compute/dynamips/nodes/router.py | python | Router.sparsemem | (self) | return self._sparsemem | Returns True if sparse memory is used on this router.
:returns: boolean either mmap is activated or not | Returns True if sparse memory is used on this router. | [
"Returns",
"True",
"if",
"sparse",
"memory",
"is",
"used",
"on",
"this",
"router",
"."
] | def sparsemem(self):
"""
Returns True if sparse memory is used on this router.
:returns: boolean either mmap is activated or not
"""
return self._sparsemem | [
"def",
"sparsemem",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sparsemem"
] | https://github.com/GNS3/gns3-server/blob/aff06572d4173df945ad29ea8feb274f7885d9e4/gns3server/compute/dynamips/nodes/router.py#L581-L588 | |
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/threading.py | python | _Event.__init__ | (self, verbose=None) | [] | def __init__(self, verbose=None):
_Verbose.__init__(self, verbose)
self.__cond = Condition(Lock())
self.__flag = False | [
"def",
"__init__",
"(",
"self",
",",
"verbose",
"=",
"None",
")",
":",
"_Verbose",
".",
"__init__",
"(",
"self",
",",
"verbose",
")",
"self",
".",
"__cond",
"=",
"Condition",
"(",
"Lock",
"(",
")",
")",
"self",
".",
"__flag",
"=",
"False"
] | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/threading.py#L561-L564 | ||||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/multiprocessing/process.py | python | _ParentProcess.is_alive | (self) | return not wait([self._sentinel], timeout=0) | [] | def is_alive(self):
from multiprocessing.connection import wait
return not wait([self._sentinel], timeout=0) | [
"def",
"is_alive",
"(",
"self",
")",
":",
"from",
"multiprocessing",
".",
"connection",
"import",
"wait",
"return",
"not",
"wait",
"(",
"[",
"self",
".",
"_sentinel",
"]",
",",
"timeout",
"=",
"0",
")"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/multiprocessing/process.py#L370-L372 | |||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_objectvalidator.py | python | Yedit.separator | (self) | return self._separator | getter method for separator | getter method for separator | [
"getter",
"method",
"for",
"separator"
] | def separator(self):
''' getter method for separator '''
return self._separator | [
"def",
"separator",
"(",
"self",
")",
":",
"return",
"self",
".",
"_separator"
] | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_objectvalidator.py#L117-L119 | |
Marten4n6/EvilOSX | 033a662030e99b3704a1505244ebc1e6e59fba57 | server/handler.py | python | _RequestHandler._send_command | (self, command_raw="") | Sends the command to the bot.
:type command_raw: str | Sends the command to the bot. | [
"Sends",
"the",
"command",
"to",
"the",
"bot",
"."
] | def _send_command(self, command_raw=""):
"""Sends the command to the bot.
:type command_raw: str
"""
response = dedent("""\
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>404 Not Found</TITLE>
</HEAD>
<BODY>
<H1>Not Found</H1>
The requested URL {} was not found on this server.
<P>
<HR>
<ADDRESS></ADDRESS>
</BODY>
</HTML>
""").format(self.path)
if command_raw != "":
response += dedent("""\
<!--
DEBUG:\n
{}DEBUG-->
""".format(command_raw))
self._send_headers()
self.wfile.write(response.encode("latin-1")) | [
"def",
"_send_command",
"(",
"self",
",",
"command_raw",
"=",
"\"\"",
")",
":",
"response",
"=",
"dedent",
"(",
"\"\"\"\\\n <!DOCTYPE html>\n <HTML>\n <HEAD>\n <TITLE>404 Not Found</TITLE>\n </HEAD>\n <BODY>\n <... | https://github.com/Marten4n6/EvilOSX/blob/033a662030e99b3704a1505244ebc1e6e59fba57/server/handler.py#L62-L91 | ||
clips/pattern | d25511f9ca7ed9356b801d8663b8b5168464e68f | pattern/server/__init__.py | python | RateLimit.count | (self, key, path="/") | Returns the current count for the given key and path. | Returns the current count for the given key and path. | [
"Returns",
"the",
"current",
"count",
"for",
"the",
"given",
"key",
"and",
"path",
"."
] | def count(self, key, path="/"):
""" Returns the current count for the given key and path.
"""
with self.lock:
p = "/" + path.strip("/")
r = self.cache.get((key, p), [0])[0]
return r | [
"def",
"count",
"(",
"self",
",",
"key",
",",
"path",
"=",
"\"/\"",
")",
":",
"with",
"self",
".",
"lock",
":",
"p",
"=",
"\"/\"",
"+",
"path",
".",
"strip",
"(",
"\"/\"",
")",
"r",
"=",
"self",
".",
"cache",
".",
"get",
"(",
"(",
"key",
",",... | https://github.com/clips/pattern/blob/d25511f9ca7ed9356b801d8663b8b5168464e68f/pattern/server/__init__.py#L633-L639 | ||
PaddlePaddle/PaddleDetection | 635e3e0a80f3d05751cdcfca8af04ee17c601a92 | ppdet/utils/visualizer.py | python | save_result | (save_path, results, catid2name, threshold) | save result as txt | save result as txt | [
"save",
"result",
"as",
"txt"
] | def save_result(save_path, results, catid2name, threshold):
"""
save result as txt
"""
img_id = int(results["im_id"])
with open(save_path, 'w') as f:
if "bbox_res" in results:
for dt in results["bbox_res"]:
catid, bbox, score = dt['category_id'], dt['bbox'], dt['score']
if score < threshold:
continue
# each bbox result as a line
# for rbox: classname score x1 y1 x2 y2 x3 y3 x4 y4
# for bbox: classname score x1 y1 w h
bbox_pred = '{} {} '.format(catid2name[catid],
score) + ' '.join(
[str(e) for e in bbox])
f.write(bbox_pred + '\n')
elif "keypoint_res" in results:
for dt in results["keypoint_res"]:
kpts = dt['keypoints']
scores = dt['score']
keypoint_pred = [img_id, scores, kpts]
print(keypoint_pred, file=f)
else:
print("No valid results found, skip txt save") | [
"def",
"save_result",
"(",
"save_path",
",",
"results",
",",
"catid2name",
",",
"threshold",
")",
":",
"img_id",
"=",
"int",
"(",
"results",
"[",
"\"im_id\"",
"]",
")",
"with",
"open",
"(",
"save_path",
",",
"'w'",
")",
"as",
"f",
":",
"if",
"\"bbox_re... | https://github.com/PaddlePaddle/PaddleDetection/blob/635e3e0a80f3d05751cdcfca8af04ee17c601a92/ppdet/utils/visualizer.py#L132-L157 | ||
tbertinmahieux/MSongsDB | 0c276e289606d5bd6f3991f713e7e9b1d4384e44 | Tasks_Demos/CoverSongs/waspaa11/fingerprint_hash.py | python | get_jump_code | (tdiff, pdiff, poffset) | return (tdiff * 12 * 12) + pdiff * 12 + poffset | Encode a jump based on a time difference and a pitch difference.
The encoding is the following:
pdiff = (pdiff + 12) % 12
code = tdiff * 12 + pdiff
tdiff of zero are accepted! | Encode a jump based on a time difference and a pitch difference.
The encoding is the following:
pdiff = (pdiff + 12) % 12
code = tdiff * 12 + pdiff
tdiff of zero are accepted! | [
"Encode",
"a",
"jump",
"based",
"on",
"a",
"time",
"difference",
"and",
"a",
"pitch",
"difference",
".",
"The",
"encoding",
"is",
"the",
"following",
":",
"pdiff",
"=",
"(",
"pdiff",
"+",
"12",
")",
"%",
"12",
"code",
"=",
"tdiff",
"*",
"12",
"+",
... | def get_jump_code(tdiff, pdiff, poffset):
"""
Encode a jump based on a time difference and a pitch difference.
The encoding is the following:
pdiff = (pdiff + 12) % 12
code = tdiff * 12 + pdiff
tdiff of zero are accepted!
"""
pdiff = (pdiff + 12) % 12
# sanity checks, should be removed for speed
assert tdiff >= 0
assert pdiff >= 0 and pdiff < 12
assert poffset >= 0 and poffset < 12
# return code
return (tdiff * 12 * 12) + pdiff * 12 + poffset | [
"def",
"get_jump_code",
"(",
"tdiff",
",",
"pdiff",
",",
"poffset",
")",
":",
"pdiff",
"=",
"(",
"pdiff",
"+",
"12",
")",
"%",
"12",
"# sanity checks, should be removed for speed",
"assert",
"tdiff",
">=",
"0",
"assert",
"pdiff",
">=",
"0",
"and",
"pdiff",
... | https://github.com/tbertinmahieux/MSongsDB/blob/0c276e289606d5bd6f3991f713e7e9b1d4384e44/Tasks_Demos/CoverSongs/waspaa11/fingerprint_hash.py#L184-L198 | |
cylc/cylc-flow | 5ec221143476c7c616c156b74158edfbcd83794a | cylc/flow/parsec/validate.py | python | parsec_validate | (cfg_root, spec_root) | return ParsecValidator().validate(cfg_root, spec_root) | Short for "ParsecValidator().validate(...)". | Short for "ParsecValidator().validate(...)". | [
"Short",
"for",
"ParsecValidator",
"()",
".",
"validate",
"(",
"...",
")",
"."
] | def parsec_validate(cfg_root, spec_root):
"""Short for "ParsecValidator().validate(...)"."""
return ParsecValidator().validate(cfg_root, spec_root) | [
"def",
"parsec_validate",
"(",
"cfg_root",
",",
"spec_root",
")",
":",
"return",
"ParsecValidator",
"(",
")",
".",
"validate",
"(",
"cfg_root",
",",
"spec_root",
")"
] | https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/parsec/validate.py#L556-L558 | |
yt-project/yt | dc7b24f9b266703db4c843e329c6c8644d47b824 | yt/utilities/command_line.py | python | YTStatsCmd.__call__ | (self, args) | [] | def __call__(self, args):
ds = args.ds
ds.print_stats()
vals = {}
field = ds._get_field_info(args.field)
if args.max:
vals["max"] = ds.find_max(field)
print(f"Maximum {field.name}: {vals['max'][0]:0.5e} at {vals['max'][1]}")
if args.min:
vals["min"] = ds.find_min(field)
print(f"Minimum {field.name}: {vals['min'][0]:0.5e} at {vals['min'][1]}")
if args.output is not None:
t = ds.current_time.to("yr")
with open(args.output, "a") as f:
f.write(f"{ds} ({t:0.5e})\n")
if "min" in vals:
f.write(
"Minimum %s is %0.5e at %s\n"
% (field.name, vals["min"][0], vals["min"][1])
)
if "max" in vals:
f.write(
"Maximum %s is %0.5e at %s\n"
% (field.name, vals["max"][0], vals["max"][1])
) | [
"def",
"__call__",
"(",
"self",
",",
"args",
")",
":",
"ds",
"=",
"args",
".",
"ds",
"ds",
".",
"print_stats",
"(",
")",
"vals",
"=",
"{",
"}",
"field",
"=",
"ds",
".",
"_get_field_info",
"(",
"args",
".",
"field",
")",
"if",
"args",
".",
"max",
... | https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/utilities/command_line.py#L1165-L1189 | ||||
makerbot/ReplicatorG | d6f2b07785a5a5f1e172fb87cb4303b17c575d5d | skein_engines/skeinforge-47/fabmetheus_utilities/geometry/manipulation_paths/round.py | python | getManipulatedPaths | (close, elementNode, loop, prefix, sideLength) | return [euclidean.getLoopWithoutCloseSequentialPoints(close, roundLoop)] | Get round loop. | Get round loop. | [
"Get",
"round",
"loop",
"."
] | def getManipulatedPaths(close, elementNode, loop, prefix, sideLength):
"Get round loop."
if len(loop) < 3:
return [loop]
derivation = RoundDerivation(elementNode, prefix, sideLength)
if derivation.radius == 0.0:
return loop
roundLoop = []
sidesPerRadian = 0.5 / math.pi * evaluate.getSidesMinimumThreeBasedOnPrecision(elementNode, sideLength)
for pointIndex in xrange(len(loop)):
begin = loop[(pointIndex + len(loop) - 1) % len(loop)]
center = loop[pointIndex]
end = loop[(pointIndex + 1) % len(loop)]
roundLoop += getRoundPath(begin, center, close, end, derivation.radius, sidesPerRadian)
return [euclidean.getLoopWithoutCloseSequentialPoints(close, roundLoop)] | [
"def",
"getManipulatedPaths",
"(",
"close",
",",
"elementNode",
",",
"loop",
",",
"prefix",
",",
"sideLength",
")",
":",
"if",
"len",
"(",
"loop",
")",
"<",
"3",
":",
"return",
"[",
"loop",
"]",
"derivation",
"=",
"RoundDerivation",
"(",
"elementNode",
"... | https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-47/fabmetheus_utilities/geometry/manipulation_paths/round.py#L26-L40 | |
dmlc/dgl | 8d14a739bc9e446d6c92ef83eafe5782398118de | examples/pytorch/cluster_gcn/utils.py | python | load_data | (args) | return data | Wraps the dgl's load_data utility to handle ppi special case | Wraps the dgl's load_data utility to handle ppi special case | [
"Wraps",
"the",
"dgl",
"s",
"load_data",
"utility",
"to",
"handle",
"ppi",
"special",
"case"
] | def load_data(args):
'''Wraps the dgl's load_data utility to handle ppi special case'''
DataType = namedtuple('Dataset', ['num_classes', 'g'])
if args.dataset != 'ppi':
dataset = _load_data(args)
data = DataType(g=dataset[0], num_classes=dataset.num_classes)
return data
train_dataset = PPIDataset('train')
train_graph = dgl.batch([train_dataset[i] for i in range(len(train_dataset))], edge_attrs=None, node_attrs=None)
val_dataset = PPIDataset('valid')
val_graph = dgl.batch([val_dataset[i] for i in range(len(val_dataset))], edge_attrs=None, node_attrs=None)
test_dataset = PPIDataset('test')
test_graph = dgl.batch([test_dataset[i] for i in range(len(test_dataset))], edge_attrs=None, node_attrs=None)
G = dgl.batch(
[train_graph, val_graph, test_graph], edge_attrs=None, node_attrs=None)
train_nodes_num = train_graph.number_of_nodes()
test_nodes_num = test_graph.number_of_nodes()
val_nodes_num = val_graph.number_of_nodes()
nodes_num = G.number_of_nodes()
assert(nodes_num == (train_nodes_num + test_nodes_num + val_nodes_num))
# construct mask
mask = np.zeros((nodes_num,), dtype=bool)
train_mask = mask.copy()
train_mask[:train_nodes_num] = True
val_mask = mask.copy()
val_mask[train_nodes_num:-test_nodes_num] = True
test_mask = mask.copy()
test_mask[-test_nodes_num:] = True
G.ndata['train_mask'] = torch.tensor(train_mask, dtype=torch.bool)
G.ndata['val_mask'] = torch.tensor(val_mask, dtype=torch.bool)
G.ndata['test_mask'] = torch.tensor(test_mask, dtype=torch.bool)
data = DataType(g=G, num_classes=train_dataset.num_labels)
return data | [
"def",
"load_data",
"(",
"args",
")",
":",
"DataType",
"=",
"namedtuple",
"(",
"'Dataset'",
",",
"[",
"'num_classes'",
",",
"'g'",
"]",
")",
"if",
"args",
".",
"dataset",
"!=",
"'ppi'",
":",
"dataset",
"=",
"_load_data",
"(",
"args",
")",
"data",
"=",
... | https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/examples/pytorch/cluster_gcn/utils.py#L61-L96 | |
ipod825/vim-netranger | 8f5864294263d86051d28b697c7ae1c480dd9ca2 | pythonx/netranger/netranger.py | python | Netranger.NETRTabBgOpen | (self) | Open the current node in a new tab, staying in the current tab. | Open the current node in a new tab, staying in the current tab. | [
"Open",
"the",
"current",
"node",
"in",
"a",
"new",
"tab",
"staying",
"in",
"the",
"current",
"tab",
"."
] | def NETRTabBgOpen(self):
""" Open the current node in a new tab, staying in the current tab.
"""
self.NETROpen('tabedit', use_rifle=False)
Vim.command('tabprevious') | [
"def",
"NETRTabBgOpen",
"(",
"self",
")",
":",
"self",
".",
"NETROpen",
"(",
"'tabedit'",
",",
"use_rifle",
"=",
"False",
")",
"Vim",
".",
"command",
"(",
"'tabprevious'",
")"
] | https://github.com/ipod825/vim-netranger/blob/8f5864294263d86051d28b697c7ae1c480dd9ca2/pythonx/netranger/netranger.py#L1528-L1532 | ||
ronf/asyncssh | ee1714c598d8c2ea6f5484e465443f38b68714aa | asyncssh/channel.py | python | SSHChannel.set_write_buffer_limits | (self, high: int = None,
low: int = None) | Set the high- and low-water limits for write flow control
This method sets the limits used when deciding when to call
the :meth:`pause_writing() <SSHClientSession.pause_writing>`
and :meth:`resume_writing() <SSHClientSession.resume_writing>`
methods on SSH sessions. Writing will be paused when the write
buffer size exceeds the high-water mark, and resumed when the
write buffer size equals or drops below the low-water mark. | Set the high- and low-water limits for write flow control | [
"Set",
"the",
"high",
"-",
"and",
"low",
"-",
"water",
"limits",
"for",
"write",
"flow",
"control"
] | def set_write_buffer_limits(self, high: int = None,
low: int = None) -> None:
"""Set the high- and low-water limits for write flow control
This method sets the limits used when deciding when to call
the :meth:`pause_writing() <SSHClientSession.pause_writing>`
and :meth:`resume_writing() <SSHClientSession.resume_writing>`
methods on SSH sessions. Writing will be paused when the write
buffer size exceeds the high-water mark, and resumed when the
write buffer size equals or drops below the low-water mark.
"""
if high is None:
high = 4*low if low is not None else 65536
if low is None:
low = high // 4
if not 0 <= low <= high:
raise ValueError('high (%r) must be >= low (%r) must be >= 0' %
(high, low))
self.logger.debug1('Set write buffer limits: low-water=%d, '
'high-water=%d', low, high)
self._send_high_water = high
self._send_low_water = low
self._pause_resume_writing() | [
"def",
"set_write_buffer_limits",
"(",
"self",
",",
"high",
":",
"int",
"=",
"None",
",",
"low",
":",
"int",
"=",
"None",
")",
"->",
"None",
":",
"if",
"high",
"is",
"None",
":",
"high",
"=",
"4",
"*",
"low",
"if",
"low",
"is",
"not",
"None",
"el... | https://github.com/ronf/asyncssh/blob/ee1714c598d8c2ea6f5484e465443f38b68714aa/asyncssh/channel.py#L848-L876 | ||
maurosoria/dirsearch | b83e68c8fdf360ab06be670d7b92b263262ee5b1 | thirdparty/pyparsing/diagram/__init__.py | python | _to_diagram_element | (
element: pyparsing.ParserElement,
parent: Optional[EditablePartial],
lookup: ConverterState = None,
vertical: int = None,
index: int = 0,
name_hint: str = None,
) | Recursively converts a PyParsing Element to a railroad Element
:param lookup: The shared converter state that keeps track of useful things
:param index: The index of this element within the parent
:param parent: The parent of this element in the output tree
:param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),
it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never
do so
:param name_hint: If provided, this will override the generated name
:returns: The converted version of the input element, but as a Partial that hasn't yet been constructed | Recursively converts a PyParsing Element to a railroad Element
:param lookup: The shared converter state that keeps track of useful things
:param index: The index of this element within the parent
:param parent: The parent of this element in the output tree
:param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),
it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never
do so
:param name_hint: If provided, this will override the generated name
:returns: The converted version of the input element, but as a Partial that hasn't yet been constructed | [
"Recursively",
"converts",
"a",
"PyParsing",
"Element",
"to",
"a",
"railroad",
"Element",
":",
"param",
"lookup",
":",
"The",
"shared",
"converter",
"state",
"that",
"keeps",
"track",
"of",
"useful",
"things",
":",
"param",
"index",
":",
"The",
"index",
"of"... | def _to_diagram_element(
element: pyparsing.ParserElement,
parent: Optional[EditablePartial],
lookup: ConverterState = None,
vertical: int = None,
index: int = 0,
name_hint: str = None,
) -> Optional[EditablePartial]:
"""
Recursively converts a PyParsing Element to a railroad Element
:param lookup: The shared converter state that keeps track of useful things
:param index: The index of this element within the parent
:param parent: The parent of this element in the output tree
:param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),
it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never
do so
:param name_hint: If provided, this will override the generated name
:returns: The converted version of the input element, but as a Partial that hasn't yet been constructed
"""
exprs = element.recurse()
name = name_hint or element.customName or element.__class__.__name__
# Python's id() is used to provide a unique identifier for elements
el_id = id(element)
# Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram
if isinstance(element, (pyparsing.Group, pyparsing.Forward)) and (
not element.customName or not exprs[0].customName
):
# However, if this element has a useful custom name, we can pass it on to the child
if not exprs[0].customName:
propagated_name = name
else:
propagated_name = None
return _to_diagram_element(
element.expr,
parent=parent,
lookup=lookup,
vertical=vertical,
index=index,
name_hint=propagated_name,
)
# If the element isn't worth extracting, we always treat it as the first time we say it
if _worth_extracting(element):
if el_id in lookup.first:
# If we've seen this element exactly once before, we are only just now finding out that it's a duplicate,
# so we have to extract it into a new diagram.
looked_up = lookup.first[el_id]
looked_up.mark_for_extraction(el_id, lookup, name=name_hint)
return EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name)
elif el_id in lookup.diagrams:
# If we have seen the element at least twice before, and have already extracted it into a subdiagram, we
# just put in a marker element that refers to the sub-diagram
return EditablePartial.from_call(
railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs["name"]
)
# Recursively convert child elements
# Here we find the most relevant Railroad element for matching pyparsing Element
# We use ``items=[]`` here to hold the place for where the child elements will go once created
if isinstance(element, pyparsing.And):
if _should_vertical(vertical, len(exprs)):
ret = EditablePartial.from_call(railroad.Stack, items=[])
else:
ret = EditablePartial.from_call(railroad.Sequence, items=[])
elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)):
if _should_vertical(vertical, len(exprs)):
ret = EditablePartial.from_call(railroad.Choice, 0, items=[])
else:
ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[])
elif isinstance(element, pyparsing.Optional):
ret = EditablePartial.from_call(railroad.Optional, item="")
elif isinstance(element, pyparsing.OneOrMore):
ret = EditablePartial.from_call(railroad.OneOrMore, item="")
elif isinstance(element, pyparsing.ZeroOrMore):
ret = EditablePartial.from_call(railroad.ZeroOrMore, item="")
elif isinstance(element, pyparsing.Group):
ret = EditablePartial.from_call(railroad.Group, item=None, label=name)
elif isinstance(element, pyparsing.Empty) and not element.customName:
# Skip unnamed "Empty" elements
ret = None
elif len(exprs) > 1:
ret = EditablePartial.from_call(railroad.Sequence, items=[])
elif len(exprs) > 0:
ret = EditablePartial.from_call(railroad.Group, item="", label=name)
else:
# If the terminal has a custom name, we annotate the terminal with it, but still show the defaultName, because
# it describes the pattern that it matches, which is useful to have present in the diagram
terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName)
if element.customName is not None:
ret = EditablePartial.from_call(
railroad.Group, item=terminal, label=element.customName
)
else:
ret = terminal
# Indicate this element's position in the tree so we can extract it if necessary
lookup.first[el_id] = ElementState(
element=element,
converted=ret,
parent=parent,
index=index,
number=lookup.generate_index(),
)
i = 0
for expr in exprs:
# Add a placeholder index in case we have to extract the child before we even add it to the parent
if "items" in ret.kwargs:
ret.kwargs["items"].insert(i, None)
item = _to_diagram_element(
expr, parent=ret, lookup=lookup, vertical=vertical, index=i
)
# Some elements don't need to be shown in the diagram
if item is not None:
if "item" in ret.kwargs:
ret.kwargs["item"] = item
elif "items" in ret.kwargs:
# If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal
if ret.kwargs["items"][i] is None:
ret.kwargs["items"][i] = item
i += 1
elif "items" in ret.kwargs:
# If we're supposed to skip this element, remove it from the parent
del ret.kwargs["items"][i]
# If all this items children are none, skip this item
if ret and (
("items" in ret.kwargs and len(ret.kwargs["items"]) == 0)
or ("item" in ret.kwargs and ret.kwargs["item"] is None)
):
return EditablePartial.from_call(railroad.Terminal, name)
# Mark this element as "complete", ie it has all of its children
if el_id in lookup.first:
lookup.first[el_id].complete = True
if (
el_id in lookup.first
and lookup.first[el_id].extract
and lookup.first[el_id].complete
):
lookup.extract_into_diagram(el_id)
return EditablePartial.from_call(
railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs["name"]
)
else:
return ret | [
"def",
"_to_diagram_element",
"(",
"element",
":",
"pyparsing",
".",
"ParserElement",
",",
"parent",
":",
"Optional",
"[",
"EditablePartial",
"]",
",",
"lookup",
":",
"ConverterState",
"=",
"None",
",",
"vertical",
":",
"int",
"=",
"None",
",",
"index",
":",... | https://github.com/maurosoria/dirsearch/blob/b83e68c8fdf360ab06be670d7b92b263262ee5b1/thirdparty/pyparsing/diagram/__init__.py#L272-L424 | ||
nanoporetech/medaka | 2b83074fe3b6a6ec971614bfc6804f543fe1e5f0 | medaka/features.py | python | BaseFeatureEncoder.__setstate__ | (self, state) | Modify object after unpickling. | Modify object after unpickling. | [
"Modify",
"object",
"after",
"unpickling",
"."
] | def __setstate__(self, state):
"""Modify object after unpickling."""
self.__dict__.update(state)
self.logger = medaka.common.get_named_logger('Feature') | [
"def",
"__setstate__",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"__dict__",
".",
"update",
"(",
"state",
")",
"self",
".",
"logger",
"=",
"medaka",
".",
"common",
".",
"get_named_logger",
"(",
"'Feature'",
")"
] | https://github.com/nanoporetech/medaka/blob/2b83074fe3b6a6ec971614bfc6804f543fe1e5f0/medaka/features.py#L390-L393 | ||
pypa/pipenv | b21baade71a86ab3ee1429f71fbc14d4f95fb75d | pipenv/vendor/charset_normalizer/models.py | python | CliDetectionResult.__dict__ | (self) | return {
"path": self.path,
"encoding": self.encoding,
"encoding_aliases": self.encoding_aliases,
"alternative_encodings": self.alternative_encodings,
"language": self.language,
"alphabets": self.alphabets,
"has_sig_or_bom": self.has_sig_or_bom,
"chaos": self.chaos,
"coherence": self.coherence,
"unicode_path": self.unicode_path,
"is_preferred": self.is_preferred,
} | [] | def __dict__(self) -> Dict[str, Any]: # type: ignore
return {
"path": self.path,
"encoding": self.encoding,
"encoding_aliases": self.encoding_aliases,
"alternative_encodings": self.alternative_encodings,
"language": self.language,
"alphabets": self.alphabets,
"has_sig_or_bom": self.has_sig_or_bom,
"chaos": self.chaos,
"coherence": self.coherence,
"unicode_path": self.unicode_path,
"is_preferred": self.is_preferred,
} | [
"def",
"__dict__",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"# type: ignore",
"return",
"{",
"\"path\"",
":",
"self",
".",
"path",
",",
"\"encoding\"",
":",
"self",
".",
"encoding",
",",
"\"encoding_aliases\"",
":",
"self",
".",
... | https://github.com/pypa/pipenv/blob/b21baade71a86ab3ee1429f71fbc14d4f95fb75d/pipenv/vendor/charset_normalizer/models.py#L377-L390 | |||
loli/medpy | 39131b94f0ab5328ab14a874229320efc2f74d98 | medpy/metric/binary.py | python | precision | (result, reference) | return precision | Precison.
Parameters
----------
result : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
reference : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
Returns
-------
precision : float
The precision between two binary datasets, here mostly binary objects in images,
which is defined as the fraction of retrieved instances that are relevant. The
precision is not symmetric.
See also
--------
:func:`recall`
Notes
-----
Not symmetric. The inverse of the precision is :func:`recall`.
High precision means that an algorithm returned substantially more relevant results than irrelevant.
References
----------
.. [1] http://en.wikipedia.org/wiki/Precision_and_recall
.. [2] http://en.wikipedia.org/wiki/Confusion_matrix#Table_of_confusion | Precison.
Parameters
----------
result : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
reference : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
Returns
-------
precision : float
The precision between two binary datasets, here mostly binary objects in images,
which is defined as the fraction of retrieved instances that are relevant. The
precision is not symmetric.
See also
--------
:func:`recall`
Notes
-----
Not symmetric. The inverse of the precision is :func:`recall`.
High precision means that an algorithm returned substantially more relevant results than irrelevant.
References
----------
.. [1] http://en.wikipedia.org/wiki/Precision_and_recall
.. [2] http://en.wikipedia.org/wiki/Confusion_matrix#Table_of_confusion | [
"Precison",
".",
"Parameters",
"----------",
"result",
":",
"array_like",
"Input",
"data",
"containing",
"objects",
".",
"Can",
"be",
"any",
"type",
"but",
"will",
"be",
"converted",
"into",
"binary",
":",
"background",
"where",
"0",
"object",
"everywhere",
"e... | def precision(result, reference):
"""
Precison.
Parameters
----------
result : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
reference : array_like
Input data containing objects. Can be any type but will be converted
into binary: background where 0, object everywhere else.
Returns
-------
precision : float
The precision between two binary datasets, here mostly binary objects in images,
which is defined as the fraction of retrieved instances that are relevant. The
precision is not symmetric.
See also
--------
:func:`recall`
Notes
-----
Not symmetric. The inverse of the precision is :func:`recall`.
High precision means that an algorithm returned substantially more relevant results than irrelevant.
References
----------
.. [1] http://en.wikipedia.org/wiki/Precision_and_recall
.. [2] http://en.wikipedia.org/wiki/Confusion_matrix#Table_of_confusion
"""
result = numpy.atleast_1d(result.astype(numpy.bool))
reference = numpy.atleast_1d(reference.astype(numpy.bool))
tp = numpy.count_nonzero(result & reference)
fp = numpy.count_nonzero(result & ~reference)
try:
precision = tp / float(tp + fp)
except ZeroDivisionError:
precision = 0.0
return precision | [
"def",
"precision",
"(",
"result",
",",
"reference",
")",
":",
"result",
"=",
"numpy",
".",
"atleast_1d",
"(",
"result",
".",
"astype",
"(",
"numpy",
".",
"bool",
")",
")",
"reference",
"=",
"numpy",
".",
"atleast_1d",
"(",
"reference",
".",
"astype",
... | https://github.com/loli/medpy/blob/39131b94f0ab5328ab14a874229320efc2f74d98/medpy/metric/binary.py#L118-L163 | |
DragonComputer/Dragonfire | dd21f8e88d9b6390bd229ff73f89a8c3c137b89c | dragonfire/deepconv/__init__.py | python | DeepConversation.mainTrain | (self, sess) | Training loop
Args:
sess: The current running session | Training loop
Args:
sess: The current running session | [
"Training",
"loop",
"Args",
":",
"sess",
":",
"The",
"current",
"running",
"session"
] | def mainTrain(self, sess):
""" Training loop
Args:
sess: The current running session
"""
# Specific training dependent loading
self.textData.makeLighter(self.ratioDataset) # Limit the number of training samples
mergedSummaries = tf.summary.merge_all() # Define the summary operator (Warning: Won't appear on the tensorboard graph)
if self.globStep == 0: # Not restoring from previous run
self.writer.add_graph(sess.graph) # First time only
# If restoring a model, restore the progression bar ? and current batch ?
print('Start training (press Ctrl+C to save and exit)...')
try: # If the user exit while training, we still try to save the model
for e in range(self.numEpochs):
print()
print("----- Epoch {}/{} ; (lr={}) -----".format(e+1, self.numEpochs, self.learningRate))
batches = self.textData.getBatches()
# TODO: Also update learning parameters eventually
tic = datetime.datetime.now()
for nextBatch in tqdm(batches, desc="Training"):
# Training pass
ops, feedDict = self.model.step(nextBatch)
assert len(ops) == 2 # training, loss
_, loss, summary = sess.run(ops + (mergedSummaries,), feedDict)
self.writer.add_summary(summary, self.globStep)
self.globStep += 1
# Output training status
if self.globStep % 100 == 0:
perplexity = math.exp(float(loss)) if loss < 300 else float("inf")
tqdm.write("----- Step %d -- Loss %.2f -- Perplexity %.2f" % (self.globStep, loss, perplexity))
# Checkpoint
if self.globStep % self.saveEvery == 0:
self._saveSession(sess)
toc = datetime.datetime.now()
print("Epoch finished in {}".format(toc-tic)) # Warning: Will overflow if an epoch takes more than 24 hours, and the output isn't really nicer
except (KeyboardInterrupt, SystemExit): # If the user press Ctrl+C while testing progress
print('Interruption detected, exiting the program...')
self._saveSession(sess) | [
"def",
"mainTrain",
"(",
"self",
",",
"sess",
")",
":",
"# Specific training dependent loading",
"self",
".",
"textData",
".",
"makeLighter",
"(",
"self",
".",
"ratioDataset",
")",
"# Limit the number of training samples",
"mergedSummaries",
"=",
"tf",
".",
"summary",... | https://github.com/DragonComputer/Dragonfire/blob/dd21f8e88d9b6390bd229ff73f89a8c3c137b89c/dragonfire/deepconv/__init__.py#L169-L221 | ||
joe42/CloudFusion | c4b94124e74a81e0634578c7754d62160081f7a1 | cloudfusion/third_party/requests_1_2_3/requests/packages/urllib3/packages/six.py | python | _import_module | (name) | return sys.modules[name] | Import module, returning the module after the last dot. | Import module, returning the module after the last dot. | [
"Import",
"module",
"returning",
"the",
"module",
"after",
"the",
"last",
"dot",
"."
] | def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name] | [
"def",
"_import_module",
"(",
"name",
")",
":",
"__import__",
"(",
"name",
")",
"return",
"sys",
".",
"modules",
"[",
"name",
"]"
] | https://github.com/joe42/CloudFusion/blob/c4b94124e74a81e0634578c7754d62160081f7a1/cloudfusion/third_party/requests_1_2_3/requests/packages/urllib3/packages/six.py#L72-L75 | |
quadrismegistus/prosodic | 2153c3bb3b9e056e03dd885e0c32e6f60cf30ec9 | prosodic/lib/lexconvert.py | python | mainopt_trymac | (i) | *<format> [<pronunciation>]
Convert phonemes from <format> into Mac and try it using the Mac OS 'say' command | *<format> [<pronunciation>]
Convert phonemes from <format> into Mac and try it using the Mac OS 'say' command | [
"*",
"<format",
">",
"[",
"<pronunciation",
">",
"]",
"Convert",
"phonemes",
"from",
"<format",
">",
"into",
"Mac",
"and",
"try",
"it",
"using",
"the",
"Mac",
"OS",
"say",
"command"
] | def mainopt_trymac(i):
"""*<format> [<pronunciation>]
Convert phonemes from <format> into Mac and try it using the Mac OS 'say' command"""
format = sys.argv[i+1]
if not format in lexFormats: return "No such format "+repr(format)+" (use --formats to see a list of formats)"
for resp in getInputText(i+2,"phonemes in "+format+" format",'maybe'):
mac = convert(resp,format,'mac')
toSay = markup_inline_word("mac",mac)
print(as_printable(toSay))
w = os.popen(macSayCommand()+" -v Vicki","w")
getBuf(w).write(toSay) | [
"def",
"mainopt_trymac",
"(",
"i",
")",
":",
"format",
"=",
"sys",
".",
"argv",
"[",
"i",
"+",
"1",
"]",
"if",
"not",
"format",
"in",
"lexFormats",
":",
"return",
"\"No such format \"",
"+",
"repr",
"(",
"format",
")",
"+",
"\" (use --formats to see a list... | https://github.com/quadrismegistus/prosodic/blob/2153c3bb3b9e056e03dd885e0c32e6f60cf30ec9/prosodic/lib/lexconvert.py#L2035-L2045 | ||
inkandswitch/livebook | 93c8d467734787366ad084fc3566bf5cbe249c51 | public/pypyjs/modules/numpy/f2py/crackfortran.py | python | crackline | (line, reset=0) | reset=-1 --- initialize
reset=0 --- crack the line
reset=1 --- final check if mismatch of blocks occured
Cracked data is saved in grouplist[0]. | reset=-1 --- initialize
reset=0 --- crack the line
reset=1 --- final check if mismatch of blocks occured | [
"reset",
"=",
"-",
"1",
"---",
"initialize",
"reset",
"=",
"0",
"---",
"crack",
"the",
"line",
"reset",
"=",
"1",
"---",
"final",
"check",
"if",
"mismatch",
"of",
"blocks",
"occured"
] | def crackline(line, reset=0):
"""
reset=-1 --- initialize
reset=0 --- crack the line
reset=1 --- final check if mismatch of blocks occured
Cracked data is saved in grouplist[0].
"""
global beginpattern, groupcounter, groupname, groupcache, grouplist
global filepositiontext, currentfilename, neededmodule, expectbegin
global skipblocksuntil, skipemptyends, previous_context, gotnextfile
if ';' in line and not (f2pyenhancementspattern[0].match(line) or
multilinepattern[0].match(line)):
for l in line.split(';'):
# XXX: non-zero reset values need testing
assert reset == 0, repr(reset)
crackline(l, reset)
return
if reset < 0:
groupcounter = 0
groupname = {groupcounter: ''}
groupcache = {groupcounter: {}}
grouplist = {groupcounter: []}
groupcache[groupcounter]['body'] = []
groupcache[groupcounter]['vars'] = {}
groupcache[groupcounter]['block'] = ''
groupcache[groupcounter]['name'] = ''
neededmodule = -1
skipblocksuntil = -1
return
if reset > 0:
fl = 0
if f77modulename and neededmodule == groupcounter:
fl = 2
while groupcounter > fl:
outmess('crackline: groupcounter=%s groupname=%s\n' %
(repr(groupcounter), repr(groupname)))
outmess(
'crackline: Mismatch of blocks encountered. Trying to fix it by assuming "end" statement.\n')
grouplist[groupcounter - 1].append(groupcache[groupcounter])
grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
del grouplist[groupcounter]
groupcounter = groupcounter - 1
if f77modulename and neededmodule == groupcounter:
grouplist[groupcounter - 1].append(groupcache[groupcounter])
grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
del grouplist[groupcounter]
groupcounter = groupcounter - 1 # end interface
grouplist[groupcounter - 1].append(groupcache[groupcounter])
grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
del grouplist[groupcounter]
groupcounter = groupcounter - 1 # end module
neededmodule = -1
return
if line == '':
return
flag = 0
for pat in [dimensionpattern, externalpattern, intentpattern, optionalpattern,
requiredpattern,
parameterpattern, datapattern, publicpattern, privatepattern,
intrisicpattern,
endifpattern, endpattern,
formatpattern,
beginpattern, functionpattern, subroutinepattern,
implicitpattern, typespattern, commonpattern,
callpattern, usepattern, containspattern,
entrypattern,
f2pyenhancementspattern,
multilinepattern
]:
m = pat[0].match(line)
if m:
break
flag = flag + 1
if not m:
re_1 = crackline_re_1
if 0 <= skipblocksuntil <= groupcounter:
return
if 'externals' in groupcache[groupcounter]:
for name in groupcache[groupcounter]['externals']:
if name in invbadnames:
name = invbadnames[name]
if 'interfaced' in groupcache[groupcounter] and name in groupcache[groupcounter]['interfaced']:
continue
m1 = re.match(
r'(?P<before>[^"]*)\b%s\b\s*@\(@(?P<args>[^@]*)@\)@.*\Z' % name, markouterparen(line), re.I)
if m1:
m2 = re_1.match(m1.group('before'))
a = _simplifyargs(m1.group('args'))
if m2:
line = 'callfun %s(%s) result (%s)' % (
name, a, m2.group('result'))
else:
line = 'callfun %s(%s)' % (name, a)
m = callfunpattern[0].match(line)
if not m:
outmess(
'crackline: could not resolve function call for line=%s.\n' % repr(line))
return
analyzeline(m, 'callfun', line)
return
if verbose > 1 or (verbose == 1 and currentfilename.lower().endswith('.pyf')):
previous_context = None
outmess('crackline:%d: No pattern for line\n' % (groupcounter))
return
elif pat[1] == 'end':
if 0 <= skipblocksuntil < groupcounter:
groupcounter = groupcounter - 1
if skipblocksuntil <= groupcounter:
return
if groupcounter <= 0:
raise Exception('crackline: groupcounter(=%s) is nonpositive. '
'Check the blocks.'
% (groupcounter))
m1 = beginpattern[0].match((line))
if (m1) and (not m1.group('this') == groupname[groupcounter]):
raise Exception('crackline: End group %s does not match with '
'previous Begin group %s\n\t%s' %
(repr(m1.group('this')), repr(groupname[groupcounter]),
filepositiontext)
)
if skipblocksuntil == groupcounter:
skipblocksuntil = -1
grouplist[groupcounter - 1].append(groupcache[groupcounter])
grouplist[groupcounter - 1][-1]['body'] = grouplist[groupcounter]
del grouplist[groupcounter]
groupcounter = groupcounter - 1
if not skipemptyends:
expectbegin = 1
elif pat[1] == 'begin':
if 0 <= skipblocksuntil <= groupcounter:
groupcounter = groupcounter + 1
return
gotnextfile = 0
analyzeline(m, pat[1], line)
expectbegin = 0
elif pat[1] == 'endif':
pass
elif pat[1] == 'contains':
if ignorecontains:
return
if 0 <= skipblocksuntil <= groupcounter:
return
skipblocksuntil = groupcounter
else:
if 0 <= skipblocksuntil <= groupcounter:
return
analyzeline(m, pat[1], line) | [
"def",
"crackline",
"(",
"line",
",",
"reset",
"=",
"0",
")",
":",
"global",
"beginpattern",
",",
"groupcounter",
",",
"groupname",
",",
"groupcache",
",",
"grouplist",
"global",
"filepositiontext",
",",
"currentfilename",
",",
"neededmodule",
",",
"expectbegin"... | https://github.com/inkandswitch/livebook/blob/93c8d467734787366ad084fc3566bf5cbe249c51/public/pypyjs/modules/numpy/f2py/crackfortran.py#L634-L782 | ||
theupdateframework/python-tuf | 45cf6076e3da7ff47968975f8106c4d6a03f9d4c | tuf/roledb.py | python | _check_rolename | (rolename, repository_name='default') | Raise securesystemslib.exceptions.FormatError if 'rolename' does not match
'tuf.formats.ROLENAME_SCHEMA',
tuf.exceptions.UnknownRoleError if 'rolename' is not found in the
role database, or securesystemslib.exceptions.InvalidNameError if
'repository_name' does not exist in the role database. | Raise securesystemslib.exceptions.FormatError if 'rolename' does not match
'tuf.formats.ROLENAME_SCHEMA',
tuf.exceptions.UnknownRoleError if 'rolename' is not found in the
role database, or securesystemslib.exceptions.InvalidNameError if
'repository_name' does not exist in the role database. | [
"Raise",
"securesystemslib",
".",
"exceptions",
".",
"FormatError",
"if",
"rolename",
"does",
"not",
"match",
"tuf",
".",
"formats",
".",
"ROLENAME_SCHEMA",
"tuf",
".",
"exceptions",
".",
"UnknownRoleError",
"if",
"rolename",
"is",
"not",
"found",
"in",
"the",
... | def _check_rolename(rolename, repository_name='default'):
""" Raise securesystemslib.exceptions.FormatError if 'rolename' does not match
'tuf.formats.ROLENAME_SCHEMA',
tuf.exceptions.UnknownRoleError if 'rolename' is not found in the
role database, or securesystemslib.exceptions.InvalidNameError if
'repository_name' does not exist in the role database.
"""
# Does 'rolename' have the correct object format?
# This check will ensure 'rolename' has the appropriate number of objects
# and object types, and that all dict keys are properly named.
formats.ROLENAME_SCHEMA.check_match(rolename)
# Does 'repository_name' have the correct format?
sslib_formats.NAME_SCHEMA.check_match(repository_name)
# Raises securesystemslib.exceptions.InvalidNameError.
_validate_rolename(rolename)
if repository_name not in _roledb_dict or repository_name not in _dirty_roles:
raise sslib_exceptions.InvalidNameError('Repository name does not'
' exist: ' + repository_name)
if rolename not in _roledb_dict[repository_name]:
raise exceptions.UnknownRoleError('Role name does not exist: ' + rolename) | [
"def",
"_check_rolename",
"(",
"rolename",
",",
"repository_name",
"=",
"'default'",
")",
":",
"# Does 'rolename' have the correct object format?",
"# This check will ensure 'rolename' has the appropriate number of objects",
"# and object types, and that all dict keys are properly named.",
... | https://github.com/theupdateframework/python-tuf/blob/45cf6076e3da7ff47968975f8106c4d6a03f9d4c/tuf/roledb.py#L967-L991 | ||
mrkipling/maraschino | c6be9286937783ae01df2d6d8cebfc8b2734a7d7 | lib/flask/app.py | python | Flask.register_error_handler | (self, code_or_exception, f) | Alternative error attach function to the :meth:`errorhandler`
decorator that is more straightforward to use for non decorator
usage.
.. versionadded:: 0.7 | Alternative error attach function to the :meth:`errorhandler`
decorator that is more straightforward to use for non decorator
usage. | [
"Alternative",
"error",
"attach",
"function",
"to",
"the",
":",
"meth",
":",
"errorhandler",
"decorator",
"that",
"is",
"more",
"straightforward",
"to",
"use",
"for",
"non",
"decorator",
"usage",
"."
] | def register_error_handler(self, code_or_exception, f):
"""Alternative error attach function to the :meth:`errorhandler`
decorator that is more straightforward to use for non decorator
usage.
.. versionadded:: 0.7
"""
self._register_error_handler(None, code_or_exception, f) | [
"def",
"register_error_handler",
"(",
"self",
",",
"code_or_exception",
",",
"f",
")",
":",
"self",
".",
"_register_error_handler",
"(",
"None",
",",
"code_or_exception",
",",
"f",
")"
] | https://github.com/mrkipling/maraschino/blob/c6be9286937783ae01df2d6d8cebfc8b2734a7d7/lib/flask/app.py#L985-L992 | ||
pulp/pulp | a0a28d804f997b6f81c391378aff2e4c90183df9 | playpen/deploy/utils/os1_utils.py | python | OS1Manager.wait_for_active_instances | (self, instance_list, timeout=10) | Wait for the given list of instances to become active. Raise an exception if any fail.
It is the responsibility of the user to tear down the instances.
:param instance_list: List of instances ids to wait on
:type instance_list: list of str
:param timeout: maximum time to wait in minutes
:type timeout: int
:raise: RuntimeError if not all the instances are in the active state by the timeout | Wait for the given list of instances to become active. Raise an exception if any fail.
It is the responsibility of the user to tear down the instances. | [
"Wait",
"for",
"the",
"given",
"list",
"of",
"instances",
"to",
"become",
"active",
".",
"Raise",
"an",
"exception",
"if",
"any",
"fail",
".",
"It",
"is",
"the",
"responsibility",
"of",
"the",
"user",
"to",
"tear",
"down",
"the",
"instances",
"."
] | def wait_for_active_instances(self, instance_list, timeout=10):
"""
Wait for the given list of instances to become active. Raise an exception if any fail.
It is the responsibility of the user to tear down the instances.
:param instance_list: List of instances ids to wait on
:type instance_list: list of str
:param timeout: maximum time to wait in minutes
:type timeout: int
:raise: RuntimeError if not all the instances are in the active state by the timeout
"""
# Wait until all the instances are built or times out
for x in range(0, timeout * 60, 10):
# Check to make sure each instance is out of the build state
for server in instance_list:
# Get the latest information about the instance
server = self.nova.servers.get(server)
# An instance isn't done building yet
if server.status == OPENSTACK_BUILD_KEYWORD:
time.sleep(10)
break
else:
# In this case every server was finished building
for server in instance_list:
server = self.nova.servers.get(server)
if server.status != OPENSTACK_ACTIVE_KEYWORD:
raise RuntimeError('Failed to build the following instance: ' + server.name)
break
else:
# In this case we never built all the instances
raise RuntimeError('Build time exceeded timeout, please inspect the instances and clean up') | [
"def",
"wait_for_active_instances",
"(",
"self",
",",
"instance_list",
",",
"timeout",
"=",
"10",
")",
":",
"# Wait until all the instances are built or times out",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"timeout",
"*",
"60",
",",
"10",
")",
":",
"# Check to ... | https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/playpen/deploy/utils/os1_utils.py#L157-L189 | ||
sz128/slot_filling_and_intent_detection_of_SLU | 40f334417a93bcfd4bb3da2cf043ab13973ae695 | models/slot_tagger_crf.py | python | LSTMTagger_CRF.__init__ | (self, embedding_dim, hidden_dim, vocab_size, tagset_size, bidirectional=True, num_layers=1, dropout=0., device=None, extFeats_dim=None, elmo_model=None, pretrained_model=None, pretrained_model_type=None, fix_pretrained_model=False) | Initialize model. | Initialize model. | [
"Initialize",
"model",
"."
] | def __init__(self, embedding_dim, hidden_dim, vocab_size, tagset_size, bidirectional=True, num_layers=1, dropout=0., device=None, extFeats_dim=None, elmo_model=None, pretrained_model=None, pretrained_model_type=None, fix_pretrained_model=False):
"""Initialize model."""
super(LSTMTagger_CRF, self).__init__()
self.embedding_dim = embedding_dim
self.hidden_dim = hidden_dim
self.vocab_size = vocab_size
self.tagset_size = tagset_size
#self.pad_token_idxs = pad_token_idxs
self.bidirectional = bidirectional
self.num_layers = num_layers
self.dropout = dropout
self.device = device
self.extFeats_dim = extFeats_dim
self.num_directions = 2 if self.bidirectional else 1
self.dropout_layer = nn.Dropout(p=self.dropout)
self.elmo_model = elmo_model
self.pretrained_model = pretrained_model
self.pretrained_model_type = pretrained_model_type
self.fix_pretrained_model = fix_pretrained_model
if self.fix_pretrained_model:
self.number_of_last_hiddens_of_pretrained = 4
self.weighted_scores_of_last_hiddens = nn.Linear(self.number_of_last_hiddens_of_pretrained, 1, bias=False)
for weight in self.pretrained_model.parameters():
weight.requires_grad = False
else:
self.number_of_last_hiddens_of_pretrained = 1
if self.elmo_model and self.pretrained_model:
self.embedding_dim = self.elmo_model.get_output_dim() + self.pretrained_model.config.hidden_size
elif self.elmo_model:
self.embedding_dim = self.elmo_model.get_output_dim()
elif self.pretrained_model:
self.embedding_dim = self.pretrained_model.config.hidden_size
else:
self.word_embeddings = nn.Embedding(self.vocab_size, self.embedding_dim)
# The LSTM takes word embeddings as inputs, and outputs hidden states
self.append_feature_dim = 0
if self.extFeats_dim:
self.append_feature_dim += self.extFeats_dim
self.extFeats_linear = nn.Linear(self.append_feature_dim, self.append_feature_dim)
else:
self.extFeats_linear = None
# with dimensionality hidden_dim.
self.lstm = nn.LSTM(self.embedding_dim + self.append_feature_dim, self.hidden_dim, num_layers=self.num_layers, bidirectional=self.bidirectional, batch_first=True, dropout=self.dropout)
# The linear layer that maps from hidden state space to tag space
self.hidden2tag = nn.Linear(self.num_directions * self.hidden_dim, self.tagset_size + 2)
self.crf_layer = crf.CRF(self.tagset_size, self.device) | [
"def",
"__init__",
"(",
"self",
",",
"embedding_dim",
",",
"hidden_dim",
",",
"vocab_size",
",",
"tagset_size",
",",
"bidirectional",
"=",
"True",
",",
"num_layers",
"=",
"1",
",",
"dropout",
"=",
"0.",
",",
"device",
"=",
"None",
",",
"extFeats_dim",
"=",... | https://github.com/sz128/slot_filling_and_intent_detection_of_SLU/blob/40f334417a93bcfd4bb3da2cf043ab13973ae695/models/slot_tagger_crf.py#L10-L61 | ||
ofnote/tsalib | e6c2ab5d1f8453866eb201264652c89d2a570f1e | models/resnet.py | python | conv3x3 | (in_planes, out_planes, stride=1) | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False) | 3x3 convolution with padding | 3x3 convolution with padding | [
"3x3",
"convolution",
"with",
"padding"
] | def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False) | [
"def",
"conv3x3",
"(",
"in_planes",
",",
"out_planes",
",",
"stride",
"=",
"1",
")",
":",
"return",
"nn",
".",
"Conv2d",
"(",
"in_planes",
",",
"out_planes",
",",
"kernel_size",
"=",
"3",
",",
"stride",
"=",
"stride",
",",
"padding",
"=",
"1",
",",
"... | https://github.com/ofnote/tsalib/blob/e6c2ab5d1f8453866eb201264652c89d2a570f1e/models/resnet.py#L28-L31 | |
cloudera/impyla | 0c736af4cad2bade9b8e313badc08ec50e81c948 | impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py | python | Client.send_get_function | (self, dbName, funcName) | [] | def send_get_function(self, dbName, funcName):
self._oprot.writeMessageBegin('get_function', TMessageType.CALL, self._seqid)
args = get_function_args()
args.dbName = dbName
args.funcName = funcName
args.write(self._oprot)
self._oprot.writeMessageEnd()
self._oprot.trans.flush() | [
"def",
"send_get_function",
"(",
"self",
",",
"dbName",
",",
"funcName",
")",
":",
"self",
".",
"_oprot",
".",
"writeMessageBegin",
"(",
"'get_function'",
",",
"TMessageType",
".",
"CALL",
",",
"self",
".",
"_seqid",
")",
"args",
"=",
"get_function_args",
"(... | https://github.com/cloudera/impyla/blob/0c736af4cad2bade9b8e313badc08ec50e81c948/impala/_thrift_gen/hive_metastore/ThriftHiveMetastore.py#L4953-L4960 | ||||
ranaroussi/pywallet | 468622dcf993a27a5b585289b2724986c02a1fbc | pywallet/utils/ethereum.py | python | Signature.x | (self) | return self.r | Convenience property for any method that requires
this object to provide a Point interface. | Convenience property for any method that requires
this object to provide a Point interface. | [
"Convenience",
"property",
"for",
"any",
"method",
"that",
"requires",
"this",
"object",
"to",
"provide",
"a",
"Point",
"interface",
"."
] | def x(self):
""" Convenience property for any method that requires
this object to provide a Point interface.
"""
return self.r | [
"def",
"x",
"(",
"self",
")",
":",
"return",
"self",
".",
"r"
] | https://github.com/ranaroussi/pywallet/blob/468622dcf993a27a5b585289b2724986c02a1fbc/pywallet/utils/ethereum.py#L937-L941 | |
smart-mobile-software/gitstack | d9fee8f414f202143eb6e620529e8e5539a2af56 | python/Lib/numbers.py | python | Real.__rmod__ | (self, other) | other % self | other % self | [
"other",
"%",
"self"
] | def __rmod__(self, other):
"""other % self"""
raise NotImplementedError | [
"def",
"__rmod__",
"(",
"self",
",",
"other",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/numbers.py#L232-L234 | ||
truenas/middleware | b11ec47d6340324f5a32287ffb4012e5d709b934 | src/middlewared/middlewared/plugins/gluster_linux/rebalance.py | python | GlusterRebalanceService.status | (self, job, data) | return await self.middleware.call('gluster.method.run', method, data) | Return the status of a rebalance operation
for a given gluster volume.
`name` String representing the gluster volume. | Return the status of a rebalance operation
for a given gluster volume. | [
"Return",
"the",
"status",
"of",
"a",
"rebalance",
"operation",
"for",
"a",
"given",
"gluster",
"volume",
"."
] | async def status(self, job, data):
"""
Return the status of a rebalance operation
for a given gluster volume.
`name` String representing the gluster volume.
"""
data = {'args': (data.pop('name'),)}
method = rebalance.status
return await self.middleware.call('gluster.method.run', method, data) | [
"async",
"def",
"status",
"(",
"self",
",",
"job",
",",
"data",
")",
":",
"data",
"=",
"{",
"'args'",
":",
"(",
"data",
".",
"pop",
"(",
"'name'",
")",
",",
")",
"}",
"method",
"=",
"rebalance",
".",
"status",
"return",
"await",
"self",
".",
"mid... | https://github.com/truenas/middleware/blob/b11ec47d6340324f5a32287ffb4012e5d709b934/src/middlewared/middlewared/plugins/gluster_linux/rebalance.py#L21-L30 | |
leo-editor/leo-editor | 383d6776d135ef17d73d935a2f0ecb3ac0e99494 | leo/external/make_stub_files.py | python | main | () | The driver for the stand-alone version of make-stub-files.
All options come from ~/stubs/make_stub_files.cfg. | The driver for the stand-alone version of make-stub-files.
All options come from ~/stubs/make_stub_files.cfg. | [
"The",
"driver",
"for",
"the",
"stand",
"-",
"alone",
"version",
"of",
"make",
"-",
"stub",
"-",
"files",
".",
"All",
"options",
"come",
"from",
"~",
"/",
"stubs",
"/",
"make_stub_files",
".",
"cfg",
"."
] | def main():
'''
The driver for the stand-alone version of make-stub-files.
All options come from ~/stubs/make_stub_files.cfg.
'''
# g.cls()
controller = StandAloneMakeStubFile()
controller.scan_command_line()
controller.scan_options()
controller.run()
print('done') | [
"def",
"main",
"(",
")",
":",
"# g.cls()",
"controller",
"=",
"StandAloneMakeStubFile",
"(",
")",
"controller",
".",
"scan_command_line",
"(",
")",
"controller",
".",
"scan_options",
"(",
")",
"controller",
".",
"run",
"(",
")",
"print",
"(",
"'done'",
")"
] | https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/external/make_stub_files.py#L82-L92 | ||
QuarkChain/pyquarkchain | af1dd06a50d918aaf45569d9b0f54f5ecceb6afe | quarkchain/cluster/shard_state.py | python | ShardState.validate_block | (
self,
block: MinorBlock,
gas_limit=None,
xshard_gas_limit=None,
validate_time=True,
) | Validate a block before running evm transactions | Validate a block before running evm transactions | [
"Validate",
"a",
"block",
"before",
"running",
"evm",
"transactions"
] | def validate_block(
self,
block: MinorBlock,
gas_limit=None,
xshard_gas_limit=None,
validate_time=True,
):
"""Validate a block before running evm transactions"""
if block.header.version != 0:
raise ValueError("incorrect minor block version")
height = block.header.height
if height < 1:
raise ValueError("unexpected height")
if not self.db.contain_minor_block_by_hash(block.header.hash_prev_minor_block):
# TODO: may put the block back to queue
raise ValueError(
"[{}] prev block not found, block height {} prev hash {}".format(
self.branch.to_str(),
height,
block.header.hash_prev_minor_block.hex(),
)
)
prev_header = self.db.get_minor_block_header_by_hash(
block.header.hash_prev_minor_block
)
if height != prev_header.height + 1:
raise ValueError("height mismatch")
if block.header.branch != self.branch:
raise ValueError("branch mismatch")
if validate_time and (
block.header.create_time
> time_ms() // 1000 + ALLOWED_FUTURE_BLOCKS_TIME_VALIDATION
):
raise ValueError("block too far into future")
if validate_time and block.header.create_time <= prev_header.create_time:
raise ValueError(
"incorrect create time tip time {}, new block time {}".format(
block.header.create_time, self.chain[-1].create_time
)
)
if block.header.hash_meta != block.meta.get_hash():
raise ValueError("hash of meta mismatch")
if (
len(block.header.extra_data)
> self.env.quark_chain_config.BLOCK_EXTRA_DATA_SIZE_LIMIT
):
raise ValueError("extra_data in block is too large")
if (
len(block.tracking_data)
> self.env.quark_chain_config.BLOCK_EXTRA_DATA_SIZE_LIMIT
):
raise ValueError("tracking_data in block is too large")
# Gas limit check
gas_limit, xshard_gas_limit = self.get_gas_limit_all(
gas_limit=gas_limit, xshard_gas_limit=xshard_gas_limit
)
if block.header.evm_gas_limit != gas_limit:
raise ValueError(
"incorrect gas limit, expected %d, actual %d"
% (gas_limit, block.header.evm_gas_limit)
)
if block.meta.evm_xshard_gas_limit >= block.header.evm_gas_limit:
raise ValueError(
"xshard_gas_limit %d should not exceed total gas_limit %d"
% (block.meta.evm_xshard_gas_limit, block.header.evm_gas_limit)
)
if block.meta.evm_xshard_gas_limit != xshard_gas_limit:
raise ValueError(
"incorrect xshard gas limit, expected %d, actual %d"
% (xshard_gas_limit, block.meta.evm_xshard_gas_limit)
)
# Make sure merkle tree is valid
merkle_hash = calculate_merkle_root(block.tx_list)
if merkle_hash != block.meta.hash_merkle_root:
raise ValueError("incorrect merkle root")
# Check the first transaction of the block
if not self.branch.is_in_branch(block.header.coinbase_address.full_shard_key):
raise ValueError("coinbase output address must be in the shard")
# Check difficulty
self.validate_diff_match_prev(block.header, prev_header)
# Check whether the root header is in the root chain
root_block_header = self.db.get_root_block_header_by_hash(
block.header.hash_prev_root_block
)
if root_block_header is None:
raise ValueError("cannot find root block for the minor block")
if (
root_block_header.height
< self.db.get_root_block_header_by_hash(
prev_header.hash_prev_root_block
).height
):
raise ValueError("prev root block height must be non-decreasing")
prev_confirmed_minor_block = (
self.db.get_last_confirmed_minor_block_header_at_root_block(
block.header.hash_prev_root_block
)
)
if prev_confirmed_minor_block and not self.__is_same_minor_chain(
prev_header, prev_confirmed_minor_block
):
raise ValueError(
"prev root block's minor block is not in the same chain as the minor block"
)
if not self.__is_same_root_chain(
self.db.get_root_block_header_by_hash(block.header.hash_prev_root_block),
self.db.get_root_block_header_by_hash(prev_header.hash_prev_root_block),
):
raise ValueError("prev root blocks are not on the same chain")
# Check PoW / PoSW
if not self.env.quark_chain_config.DISABLE_POW_CHECK:
self.validate_minor_block_seal(block) | [
"def",
"validate_block",
"(",
"self",
",",
"block",
":",
"MinorBlock",
",",
"gas_limit",
"=",
"None",
",",
"xshard_gas_limit",
"=",
"None",
",",
"validate_time",
"=",
"True",
",",
")",
":",
"if",
"block",
".",
"header",
".",
"version",
"!=",
"0",
":",
... | https://github.com/QuarkChain/pyquarkchain/blob/af1dd06a50d918aaf45569d9b0f54f5ecceb6afe/quarkchain/cluster/shard_state.py#L633-L762 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.