repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
JNRowe/jnrbase | jnrbase/human_time.py | parse_timedelta | def parse_timedelta(__delta: str) -> datetime.timedelta:
"""Parse human readable frequency.
Args:
__delta: Frequency to parse
"""
match = re.fullmatch(r"""
^(\d+(?:|\.\d+)) # value, possibly float
\ *
([hdwmy])$ # units
""", __delta, re.IGNORECASE ... | python | def parse_timedelta(__delta: str) -> datetime.timedelta:
"""Parse human readable frequency.
Args:
__delta: Frequency to parse
"""
match = re.fullmatch(r"""
^(\d+(?:|\.\d+)) # value, possibly float
\ *
([hdwmy])$ # units
""", __delta, re.IGNORECASE ... | [
"def",
"parse_timedelta",
"(",
"__delta",
":",
"str",
")",
"->",
"datetime",
".",
"timedelta",
":",
"match",
"=",
"re",
".",
"fullmatch",
"(",
"r\"\"\"\n ^(\\d+(?:|\\.\\d+)) # value, possibly float\n \\ *\n ([hdwmy])$ # units\n \"\"\"",
... | Parse human readable frequency.
Args:
__delta: Frequency to parse | [
"Parse",
"human",
"readable",
"frequency",
"."
] | train | https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/human_time.py#L74-L91 |
tBaxter/tango-articles | build/lib/articles/views.py | process_upload | def process_upload(photo_list, form, parent_object, user, status=''):
"""
Helper function that actually processes and saves the upload(s).
Segregated out for readability.
"""
status += "beginning upload processing. Gathering and normalizing fields....<br>"
for upload_file in photo_list:
... | python | def process_upload(photo_list, form, parent_object, user, status=''):
"""
Helper function that actually processes and saves the upload(s).
Segregated out for readability.
"""
status += "beginning upload processing. Gathering and normalizing fields....<br>"
for upload_file in photo_list:
... | [
"def",
"process_upload",
"(",
"photo_list",
",",
"form",
",",
"parent_object",
",",
"user",
",",
"status",
"=",
"''",
")",
":",
"status",
"+=",
"\"beginning upload processing. Gathering and normalizing fields....<br>\"",
"for",
"upload_file",
"in",
"photo_list",
":",
... | Helper function that actually processes and saves the upload(s).
Segregated out for readability. | [
"Helper",
"function",
"that",
"actually",
"processes",
"and",
"saves",
"the",
"upload",
"(",
"s",
")",
".",
"Segregated",
"out",
"for",
"readability",
"."
] | train | https://github.com/tBaxter/tango-articles/blob/93818dcca1b62042a4fc19af63474691b0fe931c/build/lib/articles/views.py#L191-L224 |
political-memory/django-representatives-votes | representatives_votes/contrib/parltrack/import_votes.py | Command.parse_vote_data | def parse_vote_data(self, vote_data):
"""
Parse data from parltrack votes db dumps (1 proposal)
"""
if 'epref' not in vote_data.keys():
logger.debug('Could not import data without epref %s',
vote_data['title'])
return
dossier_pk = self.get... | python | def parse_vote_data(self, vote_data):
"""
Parse data from parltrack votes db dumps (1 proposal)
"""
if 'epref' not in vote_data.keys():
logger.debug('Could not import data without epref %s',
vote_data['title'])
return
dossier_pk = self.get... | [
"def",
"parse_vote_data",
"(",
"self",
",",
"vote_data",
")",
":",
"if",
"'epref'",
"not",
"in",
"vote_data",
".",
"keys",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"'Could not import data without epref %s'",
",",
"vote_data",
"[",
"'title'",
"]",
")",
"re... | Parse data from parltrack votes db dumps (1 proposal) | [
"Parse",
"data",
"from",
"parltrack",
"votes",
"db",
"dumps",
"(",
"1",
"proposal",
")"
] | train | https://github.com/political-memory/django-representatives-votes/blob/97f9f29deefec05f18e51f6c38270b791b921bac/representatives_votes/contrib/parltrack/import_votes.py#L39-L58 |
political-memory/django-representatives-votes | representatives_votes/contrib/parltrack/import_votes.py | Command.parse_proposal_data | def parse_proposal_data(self, proposal_data, dossier_pk):
"""Get or Create a proposal model from raw data"""
proposal_display = '{} ({})'.format(proposal_data['title'].encode(
'utf-8'), proposal_data.get('report', '').encode('utf-8'))
if 'issue_type' not in proposal_data.keys():
... | python | def parse_proposal_data(self, proposal_data, dossier_pk):
"""Get or Create a proposal model from raw data"""
proposal_display = '{} ({})'.format(proposal_data['title'].encode(
'utf-8'), proposal_data.get('report', '').encode('utf-8'))
if 'issue_type' not in proposal_data.keys():
... | [
"def",
"parse_proposal_data",
"(",
"self",
",",
"proposal_data",
",",
"dossier_pk",
")",
":",
"proposal_display",
"=",
"'{} ({})'",
".",
"format",
"(",
"proposal_data",
"[",
"'title'",
"]",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"proposal_data",
".",
"get",
... | Get or Create a proposal model from raw data | [
"Get",
"or",
"Create",
"a",
"proposal",
"model",
"from",
"raw",
"data"
] | train | https://github.com/political-memory/django-representatives-votes/blob/97f9f29deefec05f18e51f6c38270b791b921bac/representatives_votes/contrib/parltrack/import_votes.py#L61-L159 |
bluecap-se/yarr.client | yarr_client/app.py | configurate_app | def configurate_app(config_file=''):
"""
Configures Flask app
:param config_file: Absolute path to Py config file, optional
:returns: App object, host and port
"""
# Load config
app.config.from_pyfile('defaults.py')
app.config.from_pyfile(config_file, silent=True)
if app.config.get... | python | def configurate_app(config_file=''):
"""
Configures Flask app
:param config_file: Absolute path to Py config file, optional
:returns: App object, host and port
"""
# Load config
app.config.from_pyfile('defaults.py')
app.config.from_pyfile(config_file, silent=True)
if app.config.get... | [
"def",
"configurate_app",
"(",
"config_file",
"=",
"''",
")",
":",
"# Load config",
"app",
".",
"config",
".",
"from_pyfile",
"(",
"'defaults.py'",
")",
"app",
".",
"config",
".",
"from_pyfile",
"(",
"config_file",
",",
"silent",
"=",
"True",
")",
"if",
"a... | Configures Flask app
:param config_file: Absolute path to Py config file, optional
:returns: App object, host and port | [
"Configures",
"Flask",
"app"
] | train | https://github.com/bluecap-se/yarr.client/blob/ec0c053fe8a7e92eb27b68b7a135caecde30c81d/yarr_client/app.py#L16-L43 |
bluecap-se/yarr.client | yarr_client/app.py | create_request | def create_request(query):
"""
Creates a GET request to Yarr! server
:param query: Free-text search query
:returns: Requests object
"""
yarr_url = app.config.get('YARR_URL', False)
if not yarr_url:
raise('No URL to Yarr! server specified in config.')
api_token = app.config.get... | python | def create_request(query):
"""
Creates a GET request to Yarr! server
:param query: Free-text search query
:returns: Requests object
"""
yarr_url = app.config.get('YARR_URL', False)
if not yarr_url:
raise('No URL to Yarr! server specified in config.')
api_token = app.config.get... | [
"def",
"create_request",
"(",
"query",
")",
":",
"yarr_url",
"=",
"app",
".",
"config",
".",
"get",
"(",
"'YARR_URL'",
",",
"False",
")",
"if",
"not",
"yarr_url",
":",
"raise",
"(",
"'No URL to Yarr! server specified in config.'",
")",
"api_token",
"=",
"app",... | Creates a GET request to Yarr! server
:param query: Free-text search query
:returns: Requests object | [
"Creates",
"a",
"GET",
"request",
"to",
"Yarr!",
"server"
] | train | https://github.com/bluecap-se/yarr.client/blob/ec0c053fe8a7e92eb27b68b7a135caecde30c81d/yarr_client/app.py#L46-L63 |
swgillespie/tsquare | tsquare/core.py | TSquareAPI.requires_authentication | def requires_authentication(func):
"""
Function decorator that throws an exception if the user
is not authenticated, and executes the function normally
if the user is authenticated.
"""
def _auth(self, *args, **kwargs):
if not self._authenticated:
... | python | def requires_authentication(func):
"""
Function decorator that throws an exception if the user
is not authenticated, and executes the function normally
if the user is authenticated.
"""
def _auth(self, *args, **kwargs):
if not self._authenticated:
... | [
"def",
"requires_authentication",
"(",
"func",
")",
":",
"def",
"_auth",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_authenticated",
":",
"raise",
"NotAuthenticatedException",
"(",
"'Function {} requires'",
"... | Function decorator that throws an exception if the user
is not authenticated, and executes the function normally
if the user is authenticated. | [
"Function",
"decorator",
"that",
"throws",
"an",
"exception",
"if",
"the",
"user",
"is",
"not",
"authenticated",
"and",
"executes",
"the",
"function",
"normally",
"if",
"the",
"user",
"is",
"authenticated",
"."
] | train | https://github.com/swgillespie/tsquare/blob/242adb2c27e6c65a1f75db32a4636ea3f1d22a3a/tsquare/core.py#L31-L44 |
swgillespie/tsquare | tsquare/core.py | TSquareAPI.get_user_info | def get_user_info(self):
"""
Returns a TSquareUser object representing the currently logged in user.
Throws a NotAuthenticatedException if the user is not authenticated.
"""
response = self._session.get(BASE_URL_TSQUARE + '/user/current.json')
response.raise_for_status() ... | python | def get_user_info(self):
"""
Returns a TSquareUser object representing the currently logged in user.
Throws a NotAuthenticatedException if the user is not authenticated.
"""
response = self._session.get(BASE_URL_TSQUARE + '/user/current.json')
response.raise_for_status() ... | [
"def",
"get_user_info",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"_session",
".",
"get",
"(",
"BASE_URL_TSQUARE",
"+",
"'/user/current.json'",
")",
"response",
".",
"raise_for_status",
"(",
")",
"# raises an exception if not 200: OK",
"user_data",
"=",
... | Returns a TSquareUser object representing the currently logged in user.
Throws a NotAuthenticatedException if the user is not authenticated. | [
"Returns",
"a",
"TSquareUser",
"object",
"representing",
"the",
"currently",
"logged",
"in",
"user",
".",
"Throws",
"a",
"NotAuthenticatedException",
"if",
"the",
"user",
"is",
"not",
"authenticated",
"."
] | train | https://github.com/swgillespie/tsquare/blob/242adb2c27e6c65a1f75db32a4636ea3f1d22a3a/tsquare/core.py#L75-L84 |
swgillespie/tsquare | tsquare/core.py | TSquareAPI.get_site_by_id | def get_site_by_id(self, id):
"""
Looks up a site by ID and returns a TSquareSite representing that
object, or throws an exception if no such site is found.
@param id - The entityID of the site to look up
@returns A TSquareSite object
"""
response = self._session.... | python | def get_site_by_id(self, id):
"""
Looks up a site by ID and returns a TSquareSite representing that
object, or throws an exception if no such site is found.
@param id - The entityID of the site to look up
@returns A TSquareSite object
"""
response = self._session.... | [
"def",
"get_site_by_id",
"(",
"self",
",",
"id",
")",
":",
"response",
"=",
"self",
".",
"_session",
".",
"get",
"(",
"BASE_URL_TSQUARE",
"+",
"'/site/{}.json'",
".",
"format",
"(",
"id",
")",
")",
"response",
".",
"raise_for_status",
"(",
")",
"site_data"... | Looks up a site by ID and returns a TSquareSite representing that
object, or throws an exception if no such site is found.
@param id - The entityID of the site to look up
@returns A TSquareSite object | [
"Looks",
"up",
"a",
"site",
"by",
"ID",
"and",
"returns",
"a",
"TSquareSite",
"representing",
"that",
"object",
"or",
"throws",
"an",
"exception",
"if",
"no",
"such",
"site",
"is",
"found",
"."
] | train | https://github.com/swgillespie/tsquare/blob/242adb2c27e6c65a1f75db32a4636ea3f1d22a3a/tsquare/core.py#L87-L97 |
swgillespie/tsquare | tsquare/core.py | TSquareAPI.get_sites | def get_sites(self, filter_func=lambda x: True):
"""
Returns a list of TSquareSite objects that represent the sites available
to a user.
@param filter_func - A function taking in a Site object as a parameter
that returns a True or False, depending on whether
... | python | def get_sites(self, filter_func=lambda x: True):
"""
Returns a list of TSquareSite objects that represent the sites available
to a user.
@param filter_func - A function taking in a Site object as a parameter
that returns a True or False, depending on whether
... | [
"def",
"get_sites",
"(",
"self",
",",
"filter_func",
"=",
"lambda",
"x",
":",
"True",
")",
":",
"response",
"=",
"self",
".",
"_session",
".",
"get",
"(",
"BASE_URL_TSQUARE",
"+",
"'site.json'",
")",
"response",
".",
"raise_for_status",
"(",
")",
"# raise ... | Returns a list of TSquareSite objects that represent the sites available
to a user.
@param filter_func - A function taking in a Site object as a parameter
that returns a True or False, depending on whether
or not that site should be returned by t... | [
"Returns",
"a",
"list",
"of",
"TSquareSite",
"objects",
"that",
"represent",
"the",
"sites",
"available",
"to",
"a",
"user",
"."
] | train | https://github.com/swgillespie/tsquare/blob/242adb2c27e6c65a1f75db32a4636ea3f1d22a3a/tsquare/core.py#L100-L135 |
swgillespie/tsquare | tsquare/core.py | TSquareAPI.get_announcements | def get_announcements(self, site=None, num=10, age=20):
"""
Gets announcements from a site if site is not None, or from every
site otherwise. Returns a list of TSquareAnnouncement objects.
@param site_obj (TSquareSite) If non-None, gets only the announcements
... | python | def get_announcements(self, site=None, num=10, age=20):
"""
Gets announcements from a site if site is not None, or from every
site otherwise. Returns a list of TSquareAnnouncement objects.
@param site_obj (TSquareSite) If non-None, gets only the announcements
... | [
"def",
"get_announcements",
"(",
"self",
",",
"site",
"=",
"None",
",",
"num",
"=",
"10",
",",
"age",
"=",
"20",
")",
":",
"url",
"=",
"BASE_URL_TSQUARE",
"+",
"'announcement/'",
"if",
"site",
":",
"url",
"+=",
"'site/{}.json?n={}&d={}'",
".",
"format",
... | Gets announcements from a site if site is not None, or from every
site otherwise. Returns a list of TSquareAnnouncement objects.
@param site_obj (TSquareSite) If non-None, gets only the announcements
from that site. If none, get anouncements
... | [
"Gets",
"announcements",
"from",
"a",
"site",
"if",
"site",
"is",
"not",
"None",
"or",
"from",
"every",
"site",
"otherwise",
".",
"Returns",
"a",
"list",
"of",
"TSquareAnnouncement",
"objects",
"."
] | train | https://github.com/swgillespie/tsquare/blob/242adb2c27e6c65a1f75db32a4636ea3f1d22a3a/tsquare/core.py#L138-L162 |
swgillespie/tsquare | tsquare/core.py | TSquareAPI.get_tools | def get_tools(self, site):
"""
Gets all tools associated with a site.
@param site (TSquareSite) - The site to search for tools
@returns A list of dictionaries representing Tsquare tools.
"""
# hack - gotta bypass the tsquare REST api because it kinda sucks with tools
... | python | def get_tools(self, site):
"""
Gets all tools associated with a site.
@param site (TSquareSite) - The site to search for tools
@returns A list of dictionaries representing Tsquare tools.
"""
# hack - gotta bypass the tsquare REST api because it kinda sucks with tools
... | [
"def",
"get_tools",
"(",
"self",
",",
"site",
")",
":",
"# hack - gotta bypass the tsquare REST api because it kinda sucks with tools",
"url",
"=",
"site",
".",
"entityURL",
".",
"replace",
"(",
"'direct'",
",",
"'portal'",
")",
"response",
"=",
"self",
".",
"_sessi... | Gets all tools associated with a site.
@param site (TSquareSite) - The site to search for tools
@returns A list of dictionaries representing Tsquare tools. | [
"Gets",
"all",
"tools",
"associated",
"with",
"a",
"site",
"."
] | train | https://github.com/swgillespie/tsquare/blob/242adb2c27e6c65a1f75db32a4636ea3f1d22a3a/tsquare/core.py#L165-L177 |
swgillespie/tsquare | tsquare/core.py | TSquareAPI.get_assignments | def get_assignments(self, site):
"""
Gets a list of assignments associated with a site (class). Returns
a list of TSquareAssignment objects.
@param site (TSquareSite) - The site to use with the assignment query
@returns - A list of TSquareSite objects. May be an empty list if
... | python | def get_assignments(self, site):
"""
Gets a list of assignments associated with a site (class). Returns
a list of TSquareAssignment objects.
@param site (TSquareSite) - The site to use with the assignment query
@returns - A list of TSquareSite objects. May be an empty list if
... | [
"def",
"get_assignments",
"(",
"self",
",",
"site",
")",
":",
"tools",
"=",
"self",
".",
"get_tools",
"(",
"site",
")",
"assignment_tool_filter",
"=",
"[",
"x",
".",
"href",
"for",
"x",
"in",
"tools",
"if",
"x",
".",
"name",
"==",
"'assignment-grades'",
... | Gets a list of assignments associated with a site (class). Returns
a list of TSquareAssignment objects.
@param site (TSquareSite) - The site to use with the assignment query
@returns - A list of TSquareSite objects. May be an empty list if
the site has defined no assignments. | [
"Gets",
"a",
"list",
"of",
"assignments",
"associated",
"with",
"a",
"site",
"(",
"class",
")",
".",
"Returns",
"a",
"list",
"of",
"TSquareAssignment",
"objects",
".",
"@param",
"site",
"(",
"TSquareSite",
")",
"-",
"The",
"site",
"to",
"use",
"with",
"t... | train | https://github.com/swgillespie/tsquare/blob/242adb2c27e6c65a1f75db32a4636ea3f1d22a3a/tsquare/core.py#L180-L206 |
swgillespie/tsquare | tsquare/core.py | TSquareAPI.get_grades | def get_grades(self, site):
"""
Gets a list of grades associated with a site. The return type is a dictionary
whose keys are assignment categories, similar to how the page is laid out
in TSquare.
"""
tools = self.get_tools(site)
grade_tool_filter = [x.href for x i... | python | def get_grades(self, site):
"""
Gets a list of grades associated with a site. The return type is a dictionary
whose keys are assignment categories, similar to how the page is laid out
in TSquare.
"""
tools = self.get_tools(site)
grade_tool_filter = [x.href for x i... | [
"def",
"get_grades",
"(",
"self",
",",
"site",
")",
":",
"tools",
"=",
"self",
".",
"get_tools",
"(",
"site",
")",
"grade_tool_filter",
"=",
"[",
"x",
".",
"href",
"for",
"x",
"in",
"tools",
"if",
"x",
".",
"name",
"==",
"'gradebook-tool'",
"]",
"if"... | Gets a list of grades associated with a site. The return type is a dictionary
whose keys are assignment categories, similar to how the page is laid out
in TSquare. | [
"Gets",
"a",
"list",
"of",
"grades",
"associated",
"with",
"a",
"site",
".",
"The",
"return",
"type",
"is",
"a",
"dictionary",
"whose",
"keys",
"are",
"assignment",
"categories",
"similar",
"to",
"how",
"the",
"page",
"is",
"laid",
"out",
"in",
"TSquare",
... | train | https://github.com/swgillespie/tsquare/blob/242adb2c27e6c65a1f75db32a4636ea3f1d22a3a/tsquare/core.py#L209-L231 |
swgillespie/tsquare | tsquare/core.py | TSquareAPI.get_syllabus | def get_syllabus(self, site):
"""
Gets the syllabus for a course. The syllabus may or may not
contain HTML, depending on the site. TSquare does not enforce
whether or not pages are allowed to have HTML, so it is impossible
to tell.
"""
tools = self.get_tools(site)... | python | def get_syllabus(self, site):
"""
Gets the syllabus for a course. The syllabus may or may not
contain HTML, depending on the site. TSquare does not enforce
whether or not pages are allowed to have HTML, so it is impossible
to tell.
"""
tools = self.get_tools(site)... | [
"def",
"get_syllabus",
"(",
"self",
",",
"site",
")",
":",
"tools",
"=",
"self",
".",
"get_tools",
"(",
"site",
")",
"syllabus_filter",
"=",
"[",
"x",
".",
"href",
"for",
"x",
"in",
"tools",
"if",
"x",
".",
"name",
"==",
"'syllabus'",
"]",
"if",
"n... | Gets the syllabus for a course. The syllabus may or may not
contain HTML, depending on the site. TSquare does not enforce
whether or not pages are allowed to have HTML, so it is impossible
to tell. | [
"Gets",
"the",
"syllabus",
"for",
"a",
"course",
".",
"The",
"syllabus",
"may",
"or",
"may",
"not",
"contain",
"HTML",
"depending",
"on",
"the",
"site",
".",
"TSquare",
"does",
"not",
"enforce",
"whether",
"or",
"not",
"pages",
"are",
"allowed",
"to",
"h... | train | https://github.com/swgillespie/tsquare/blob/242adb2c27e6c65a1f75db32a4636ea3f1d22a3a/tsquare/core.py#L234-L257 |
FlorianLudwig/rueckenwind | rw/scope.py | setup_app_scope | def setup_app_scope(name, scope):
"""activate plugins accordingly to config"""
# load plugins
plugins = []
for plugin_name, active in get('settings').get('rw.plugins', {}).items():
plugin = __import__(plugin_name)
plugin_path = plugin_name.split('.')[1:] + ['plugin']
for sub in ... | python | def setup_app_scope(name, scope):
"""activate plugins accordingly to config"""
# load plugins
plugins = []
for plugin_name, active in get('settings').get('rw.plugins', {}).items():
plugin = __import__(plugin_name)
plugin_path = plugin_name.split('.')[1:] + ['plugin']
for sub in ... | [
"def",
"setup_app_scope",
"(",
"name",
",",
"scope",
")",
":",
"# load plugins",
"plugins",
"=",
"[",
"]",
"for",
"plugin_name",
",",
"active",
"in",
"get",
"(",
"'settings'",
")",
".",
"get",
"(",
"'rw.plugins'",
",",
"{",
"}",
")",
".",
"items",
"(",... | activate plugins accordingly to config | [
"activate",
"plugins",
"accordingly",
"to",
"config"
] | train | https://github.com/FlorianLudwig/rueckenwind/blob/47fec7af05ea10b3cf6d59b9f7bf4d12c02dddea/rw/scope.py#L181-L194 |
MacHu-GWU/angora-project | angora/gadget/configuration.py | Configuration.add_section | def add_section(self, section_name):
"""Add an empty section.
"""
if section_name == "DEFAULT":
raise Exception("'DEFAULT' is reserved section name.")
if section_name in self._sections:
raise Exception(
"Error! %s is already one of the sections" %... | python | def add_section(self, section_name):
"""Add an empty section.
"""
if section_name == "DEFAULT":
raise Exception("'DEFAULT' is reserved section name.")
if section_name in self._sections:
raise Exception(
"Error! %s is already one of the sections" %... | [
"def",
"add_section",
"(",
"self",
",",
"section_name",
")",
":",
"if",
"section_name",
"==",
"\"DEFAULT\"",
":",
"raise",
"Exception",
"(",
"\"'DEFAULT' is reserved section name.\"",
")",
"if",
"section_name",
"in",
"self",
".",
"_sections",
":",
"raise",
"Except... | Add an empty section. | [
"Add",
"an",
"empty",
"section",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/configuration.py#L253-L263 |
MacHu-GWU/angora-project | angora/gadget/configuration.py | Configuration.remove_section | def remove_section(self, section_name):
"""Remove a section, it cannot be the DEFAULT section.
"""
if section_name == "DEFAULT":
raise Exception("'DEFAULT' is reserved section name.")
if section_name in self._sections:
del self._sections[section_name]
els... | python | def remove_section(self, section_name):
"""Remove a section, it cannot be the DEFAULT section.
"""
if section_name == "DEFAULT":
raise Exception("'DEFAULT' is reserved section name.")
if section_name in self._sections:
del self._sections[section_name]
els... | [
"def",
"remove_section",
"(",
"self",
",",
"section_name",
")",
":",
"if",
"section_name",
"==",
"\"DEFAULT\"",
":",
"raise",
"Exception",
"(",
"\"'DEFAULT' is reserved section name.\"",
")",
"if",
"section_name",
"in",
"self",
".",
"_sections",
":",
"del",
"self"... | Remove a section, it cannot be the DEFAULT section. | [
"Remove",
"a",
"section",
"it",
"cannot",
"be",
"the",
"DEFAULT",
"section",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/configuration.py#L265-L274 |
MacHu-GWU/angora-project | angora/gadget/configuration.py | Configuration.set_section | def set_section(self, section):
"""Set a section. If section already exists, overwrite the old one.
"""
if not isinstance(section, Section):
raise Exception("You")
try:
self.remove_section(section.name)
except:
pass
self._sections[sec... | python | def set_section(self, section):
"""Set a section. If section already exists, overwrite the old one.
"""
if not isinstance(section, Section):
raise Exception("You")
try:
self.remove_section(section.name)
except:
pass
self._sections[sec... | [
"def",
"set_section",
"(",
"self",
",",
"section",
")",
":",
"if",
"not",
"isinstance",
"(",
"section",
",",
"Section",
")",
":",
"raise",
"Exception",
"(",
"\"You\"",
")",
"try",
":",
"self",
".",
"remove_section",
"(",
"section",
".",
"name",
")",
"e... | Set a section. If section already exists, overwrite the old one. | [
"Set",
"a",
"section",
".",
"If",
"section",
"already",
"exists",
"overwrite",
"the",
"old",
"one",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/configuration.py#L276-L287 |
MacHu-GWU/angora-project | angora/gadget/configuration.py | Configuration.load | def load(self, path):
"""Read configuration from file.
"""
with open(path, "rb") as f:
content = f.read().decode("utf-8")
section_text_list = list()
lines = list()
for line in content.split("\n"):
if line.startswith("["):
section_... | python | def load(self, path):
"""Read configuration from file.
"""
with open(path, "rb") as f:
content = f.read().decode("utf-8")
section_text_list = list()
lines = list()
for line in content.split("\n"):
if line.startswith("["):
section_... | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"read",
"(",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"section_text_list",
"=",
"list",
"(",
")",
"lin... | Read configuration from file. | [
"Read",
"configuration",
"from",
"file",
"."
] | train | https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/configuration.py#L306-L328 |
timeyyy/apptools | peasoup/peasoup.py | setup_logger | def setup_logger(log_file, level=logging.DEBUG):
'''One function call to set up logging with some nice logs about the machine'''
cfg = AppBuilder.get_pcfg()
logger = cfg['log_module']
# todo make sure structlog is compliant and that logbook is also the correct name???
assert logger in ("logging", "l... | python | def setup_logger(log_file, level=logging.DEBUG):
'''One function call to set up logging with some nice logs about the machine'''
cfg = AppBuilder.get_pcfg()
logger = cfg['log_module']
# todo make sure structlog is compliant and that logbook is also the correct name???
assert logger in ("logging", "l... | [
"def",
"setup_logger",
"(",
"log_file",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"cfg",
"=",
"AppBuilder",
".",
"get_pcfg",
"(",
")",
"logger",
"=",
"cfg",
"[",
"'log_module'",
"]",
"# todo make sure structlog is compliant and that logbook is also the c... | One function call to set up logging with some nice logs about the machine | [
"One",
"function",
"call",
"to",
"set",
"up",
"logging",
"with",
"some",
"nice",
"logs",
"about",
"the",
"machine"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L424-L443 |
timeyyy/apptools | peasoup/peasoup.py | set_windows_permissions | def set_windows_permissions(filename):
'''
At least on windows 7 if a file is created on an Admin account,
Other users will not be given execute or full control.
However if a user creates the file himself it will work...
So just always change permissions after creating a file on windows
Change ... | python | def set_windows_permissions(filename):
'''
At least on windows 7 if a file is created on an Admin account,
Other users will not be given execute or full control.
However if a user creates the file himself it will work...
So just always change permissions after creating a file on windows
Change ... | [
"def",
"set_windows_permissions",
"(",
"filename",
")",
":",
"#Todo rename this to allow_all, also make international not just for english..",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"try",
":",
"everyone",
",",
"domain",
",",
"type",
"=",
"win32security",
".",
"L... | At least on windows 7 if a file is created on an Admin account,
Other users will not be given execute or full control.
However if a user creates the file himself it will work...
So just always change permissions after creating a file on windows
Change the permissions for Allusers of the application
... | [
"At",
"least",
"on",
"windows",
"7",
"if",
"a",
"file",
"is",
"created",
"on",
"an",
"Admin",
"account",
"Other",
"users",
"will",
"not",
"be",
"given",
"execute",
"or",
"full",
"control",
".",
"However",
"if",
"a",
"user",
"creates",
"the",
"file",
"h... | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L446-L489 |
timeyyy/apptools | peasoup/peasoup.py | setup_raven | def setup_raven():
'''we setup sentry to get all stuff from our logs'''
pcfg = AppBuilder.get_pcfg()
from raven.handlers.logging import SentryHandler
from raven import Client
from raven.conf import setup_logging
client = Client(pcfg['raven_dsn'])
handler = SentryHandler(client)
# TODO VE... | python | def setup_raven():
'''we setup sentry to get all stuff from our logs'''
pcfg = AppBuilder.get_pcfg()
from raven.handlers.logging import SentryHandler
from raven import Client
from raven.conf import setup_logging
client = Client(pcfg['raven_dsn'])
handler = SentryHandler(client)
# TODO VE... | [
"def",
"setup_raven",
"(",
")",
":",
"pcfg",
"=",
"AppBuilder",
".",
"get_pcfg",
"(",
")",
"from",
"raven",
".",
"handlers",
".",
"logging",
"import",
"SentryHandler",
"from",
"raven",
"import",
"Client",
"from",
"raven",
".",
"conf",
"import",
"setup_loggin... | we setup sentry to get all stuff from our logs | [
"we",
"setup",
"sentry",
"to",
"get",
"all",
"stuff",
"from",
"our",
"logs"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L492-L503 |
timeyyy/apptools | peasoup/peasoup.py | CfgDict.save | def save(self):
'''saves our config objet to file'''
if self.app.cfg_mode == 'json':
with open(self.app.cfg_file, 'w') as opened_file:
json.dump(self.app.cfg, opened_file)
else:
with open(self.app.cfg_file, 'w')as opened_file:
yaml.dump(sel... | python | def save(self):
'''saves our config objet to file'''
if self.app.cfg_mode == 'json':
with open(self.app.cfg_file, 'w') as opened_file:
json.dump(self.app.cfg, opened_file)
else:
with open(self.app.cfg_file, 'w')as opened_file:
yaml.dump(sel... | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"app",
".",
"cfg_mode",
"==",
"'json'",
":",
"with",
"open",
"(",
"self",
".",
"app",
".",
"cfg_file",
",",
"'w'",
")",
"as",
"opened_file",
":",
"json",
".",
"dump",
"(",
"self",
".",
"app... | saves our config objet to file | [
"saves",
"our",
"config",
"objet",
"to",
"file"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L64-L71 |
timeyyy/apptools | peasoup/peasoup.py | AppBuilder.get_pcfg | def get_pcfg():
'''
sets up the config options by reading globals saved in peasoup/global.py
as self.pcfg
'''
path = os.path.dirname(AppBuilder.main_file)
file = os.path.join(path,
PEASOUP_USER_DIR,
PEASOUP_CONFIG_FI... | python | def get_pcfg():
'''
sets up the config options by reading globals saved in peasoup/global.py
as self.pcfg
'''
path = os.path.dirname(AppBuilder.main_file)
file = os.path.join(path,
PEASOUP_USER_DIR,
PEASOUP_CONFIG_FI... | [
"def",
"get_pcfg",
"(",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"AppBuilder",
".",
"main_file",
")",
"file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"PEASOUP_USER_DIR",
",",
"PEASOUP_CONFIG_FILE",
")",
"with",
"ope... | sets up the config options by reading globals saved in peasoup/global.py
as self.pcfg | [
"sets",
"up",
"the",
"config",
"options",
"by",
"reading",
"globals",
"saved",
"in",
"peasoup",
"/",
"global",
".",
"py",
"as",
"self",
".",
"pcfg"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L93-L104 |
timeyyy/apptools | peasoup/peasoup.py | AppBuilder.create_cfg | def create_cfg(self, cfg_file, defaults=None, mode='json'):
'''
set mode to json or yaml? probably remove this option..Todo
Creates the config file for your app with default values
The file will only be created if it doesn't exits
also sets up the first_run attribute.
... | python | def create_cfg(self, cfg_file, defaults=None, mode='json'):
'''
set mode to json or yaml? probably remove this option..Todo
Creates the config file for your app with default values
The file will only be created if it doesn't exits
also sets up the first_run attribute.
... | [
"def",
"create_cfg",
"(",
"self",
",",
"cfg_file",
",",
"defaults",
"=",
"None",
",",
"mode",
"=",
"'json'",
")",
":",
"assert",
"mode",
"in",
"(",
"'json'",
",",
"'yaml'",
")",
"self",
".",
"cfg_mode",
"=",
"mode",
"self",
".",
"cfg_file",
"=",
"cfg... | set mode to json or yaml? probably remove this option..Todo
Creates the config file for your app with default values
The file will only be created if it doesn't exits
also sets up the first_run attribute.
also sets correct windows permissions
you can add custom stuff to the c... | [
"set",
"mode",
"to",
"json",
"or",
"yaml?",
"probably",
"remove",
"this",
"option",
"..",
"Todo"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L106-L142 |
timeyyy/apptools | peasoup/peasoup.py | AppBuilder.load_cfg | def load_cfg(self):
'''loads our config object accessible via self.cfg'''
if self.cfg_mode == 'json':
with open(self.cfg_file) as opened_file:
return json.load(opened_file)
else:
with open(self.cfg_file) as ymlfile:
return yaml.safe_load(ym... | python | def load_cfg(self):
'''loads our config object accessible via self.cfg'''
if self.cfg_mode == 'json':
with open(self.cfg_file) as opened_file:
return json.load(opened_file)
else:
with open(self.cfg_file) as ymlfile:
return yaml.safe_load(ym... | [
"def",
"load_cfg",
"(",
"self",
")",
":",
"if",
"self",
".",
"cfg_mode",
"==",
"'json'",
":",
"with",
"open",
"(",
"self",
".",
"cfg_file",
")",
"as",
"opened_file",
":",
"return",
"json",
".",
"load",
"(",
"opened_file",
")",
"else",
":",
"with",
"o... | loads our config object accessible via self.cfg | [
"loads",
"our",
"config",
"object",
"accessible",
"via",
"self",
".",
"cfg"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L144-L151 |
timeyyy/apptools | peasoup/peasoup.py | AppBuilder._check_first_run | def _check_first_run(self):
'''
Checks if this is the first time our app is being run
This is called automatically when using create_cfg()
use then app.first_run attribute to check for True or False
'''
if self.cfg['first_run']:
self.cfg['first_run'] = False
... | python | def _check_first_run(self):
'''
Checks if this is the first time our app is being run
This is called automatically when using create_cfg()
use then app.first_run attribute to check for True or False
'''
if self.cfg['first_run']:
self.cfg['first_run'] = False
... | [
"def",
"_check_first_run",
"(",
"self",
")",
":",
"if",
"self",
".",
"cfg",
"[",
"'first_run'",
"]",
":",
"self",
".",
"cfg",
"[",
"'first_run'",
"]",
"=",
"False",
"self",
".",
"cfg",
".",
"save",
"(",
")",
"return",
"True",
"else",
":",
"return",
... | Checks if this is the first time our app is being run
This is called automatically when using create_cfg()
use then app.first_run attribute to check for True or False | [
"Checks",
"if",
"this",
"is",
"the",
"first",
"time",
"our",
"app",
"is",
"being",
"run",
"This",
"is",
"called",
"automatically",
"when",
"using",
"create_cfg",
"()",
"use",
"then",
"app",
".",
"first_run",
"attribute",
"to",
"check",
"for",
"True",
"or",... | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L154-L165 |
timeyyy/apptools | peasoup/peasoup.py | AppBuilder.get_appdir | def get_appdir(self, portable_path=None, folder=None, create=False):
'''
path = uac_bypass(file)
This function will only operate when your program is installed
check the is_installed function for details
Moves working data to another folder. The idea is to get around
se... | python | def get_appdir(self, portable_path=None, folder=None, create=False):
'''
path = uac_bypass(file)
This function will only operate when your program is installed
check the is_installed function for details
Moves working data to another folder. The idea is to get around
se... | [
"def",
"get_appdir",
"(",
"self",
",",
"portable_path",
"=",
"None",
",",
"folder",
"=",
"None",
",",
"create",
"=",
"False",
")",
":",
"if",
"self",
".",
"is_installed",
"(",
")",
":",
"appdir",
"=",
"appdirs",
".",
"user_data_dir",
"(",
"self",
".",
... | path = uac_bypass(file)
This function will only operate when your program is installed
check the is_installed function for details
Moves working data to another folder. The idea is to get around
security and uac on windows vista +
returns cwd on linux, windows returns path wit... | [
"path",
"=",
"uac_bypass",
"(",
"file",
")"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L183-L233 |
timeyyy/apptools | peasoup/peasoup.py | AppBuilder.check_if_open | def check_if_open(self, path=None, appdata=False, verbose=False):
'''
Allows only one version of the app to be open at a time.
If you are calling create_cfg() before calling this,
you don't need to give a path. Otherwise a file path must be
given so we can save our file there.
... | python | def check_if_open(self, path=None, appdata=False, verbose=False):
'''
Allows only one version of the app to be open at a time.
If you are calling create_cfg() before calling this,
you don't need to give a path. Otherwise a file path must be
given so we can save our file there.
... | [
"def",
"check_if_open",
"(",
"self",
",",
"path",
"=",
"None",
",",
"appdata",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"#~ To know if the system crashed, or if the prgram was exited smoothly",
"#~ turn verbose to True and the function will return a named tuple # ... | Allows only one version of the app to be open at a time.
If you are calling create_cfg() before calling this,
you don't need to give a path. Otherwise a file path must be
given so we can save our file there.
Set appdata to True to run uac_bypass on the path, otherwise
leave it ... | [
"Allows",
"only",
"one",
"version",
"of",
"the",
"app",
"to",
"be",
"open",
"at",
"a",
"time",
"."
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L256-L287 |
timeyyy/apptools | peasoup/peasoup.py | AppBuilder.release_singleton | def release_singleton(self):
'''deletes the data that lets our program know if it is
running as singleton when calling check_if_open,
i.e check_if_open will return fals after calling this
'''
with suppress(KeyError):
del self.cfg['is_programming_running_info']
... | python | def release_singleton(self):
'''deletes the data that lets our program know if it is
running as singleton when calling check_if_open,
i.e check_if_open will return fals after calling this
'''
with suppress(KeyError):
del self.cfg['is_programming_running_info']
... | [
"def",
"release_singleton",
"(",
"self",
")",
":",
"with",
"suppress",
"(",
"KeyError",
")",
":",
"del",
"self",
".",
"cfg",
"[",
"'is_programming_running_info'",
"]",
"with",
"suppress",
"(",
"FileNotFoundError",
",",
"AttributeError",
")",
":",
"os",
".",
... | deletes the data that lets our program know if it is
running as singleton when calling check_if_open,
i.e check_if_open will return fals after calling this | [
"deletes",
"the",
"data",
"that",
"lets",
"our",
"program",
"know",
"if",
"it",
"is",
"running",
"as",
"singleton",
"when",
"calling",
"check_if_open",
"i",
".",
"e",
"check_if_open",
"will",
"return",
"fals",
"after",
"calling",
"this"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L289-L297 |
timeyyy/apptools | peasoup/peasoup.py | AppBuilder.shutdown | def shutdown(self):
''' shutdown operations on exit, this is run by
a finaly statement after the tkinter mainloop ends
call root.quit to get here,
Note you will still need to call sys.exit()
'''
logging.info('Shutdown procedures being run!')
for func in self.shutd... | python | def shutdown(self):
''' shutdown operations on exit, this is run by
a finaly statement after the tkinter mainloop ends
call root.quit to get here,
Note you will still need to call sys.exit()
'''
logging.info('Shutdown procedures being run!')
for func in self.shutd... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Shutdown procedures being run!'",
")",
"for",
"func",
"in",
"self",
".",
"shutdown_cleanup",
".",
"values",
"(",
")",
":",
"func",
"(",
")",
"session_time",
"=",
"round",
"(",
"(",
... | shutdown operations on exit, this is run by
a finaly statement after the tkinter mainloop ends
call root.quit to get here,
Note you will still need to call sys.exit() | [
"shutdown",
"operations",
"on",
"exit",
"this",
"is",
"run",
"by",
"a",
"finaly",
"statement",
"after",
"the",
"tkinter",
"mainloop",
"ends",
"call",
"root",
".",
"quit",
"to",
"get",
"here",
"Note",
"you",
"will",
"still",
"need",
"to",
"call",
"sys",
"... | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L391-L402 |
timeyyy/apptools | peasoup/peasoup.py | AppBuilder.rel_path | def rel_path(*file_path):
'''
gives relative paths to files, works when frozen or unfrozen
to get the root path just pass in the string __file__
'''
if hasattr(sys, 'frozen'):
if file_path[0] == '__file__':
return sys.executable
return os.p... | python | def rel_path(*file_path):
'''
gives relative paths to files, works when frozen or unfrozen
to get the root path just pass in the string __file__
'''
if hasattr(sys, 'frozen'):
if file_path[0] == '__file__':
return sys.executable
return os.p... | [
"def",
"rel_path",
"(",
"*",
"file_path",
")",
":",
"if",
"hasattr",
"(",
"sys",
",",
"'frozen'",
")",
":",
"if",
"file_path",
"[",
"0",
"]",
"==",
"'__file__'",
":",
"return",
"sys",
".",
"executable",
"return",
"os",
".",
"path",
".",
"join",
"(",
... | gives relative paths to files, works when frozen or unfrozen
to get the root path just pass in the string __file__ | [
"gives",
"relative",
"paths",
"to",
"files",
"works",
"when",
"frozen",
"or",
"unfrozen",
"to",
"get",
"the",
"root",
"path",
"just",
"pass",
"in",
"the",
"string",
"__file__"
] | train | https://github.com/timeyyy/apptools/blob/d3c0f324b0c2689c35f5601348276f4efd6cb240/peasoup/peasoup.py#L405-L422 |
zlobspb/txtarantool | txtarantool.py | Request.pack_int_base128 | def pack_int_base128(cls, value):
"""
Pack integer value using LEB128 encoding
:param value: integer value to encode
:type value: int
:return: encoded value
:rtype: bytes
"""
assert isinstance(value, int)
if value < 1 << 14:
return cls... | python | def pack_int_base128(cls, value):
"""
Pack integer value using LEB128 encoding
:param value: integer value to encode
:type value: int
:return: encoded value
:rtype: bytes
"""
assert isinstance(value, int)
if value < 1 << 14:
return cls... | [
"def",
"pack_int_base128",
"(",
"cls",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"int",
")",
"if",
"value",
"<",
"1",
"<<",
"14",
":",
"return",
"cls",
".",
"_int_base128",
"[",
"value",
"]",
"if",
"value",
"<",
"1",
"<<",
... | Pack integer value using LEB128 encoding
:param value: integer value to encode
:type value: int
:return: encoded value
:rtype: bytes | [
"Pack",
"integer",
"value",
"using",
"LEB128",
"encoding",
":",
"param",
"value",
":",
"integer",
"value",
"to",
"encode",
":",
"type",
"value",
":",
"int"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L156-L193 |
zlobspb/txtarantool | txtarantool.py | Request.pack_str | def pack_str(cls, value):
"""
Pack string field
<field> ::= <int32_varint><data>
:param value: string to be packed
:type value: bytes or str
:return: packed value
:rtype: bytes
"""
assert isinstance(value, str)
value_len_packed = cls.pack... | python | def pack_str(cls, value):
"""
Pack string field
<field> ::= <int32_varint><data>
:param value: string to be packed
:type value: bytes or str
:return: packed value
:rtype: bytes
"""
assert isinstance(value, str)
value_len_packed = cls.pack... | [
"def",
"pack_str",
"(",
"cls",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"str",
")",
"value_len_packed",
"=",
"cls",
".",
"pack_int_base128",
"(",
"len",
"(",
"value",
")",
")",
"return",
"struct",
".",
"pack",
"(",
"\"<%ds%ds\""... | Pack string field
<field> ::= <int32_varint><data>
:param value: string to be packed
:type value: bytes or str
:return: packed value
:rtype: bytes | [
"Pack",
"string",
"field",
"<field",
">",
"::",
"=",
"<int32_varint",
">",
"<data",
">"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L196-L209 |
zlobspb/txtarantool | txtarantool.py | Request.pack_unicode | def pack_unicode(cls, value, charset="utf-8", errors="strict"):
"""
Pack string field
<field> ::= <int32_varint><data>
:param value: string to be packed
:type value: unicode
:return: packed value
:rtype: bytes
"""
assert isinstance(value, unicode... | python | def pack_unicode(cls, value, charset="utf-8", errors="strict"):
"""
Pack string field
<field> ::= <int32_varint><data>
:param value: string to be packed
:type value: unicode
:return: packed value
:rtype: bytes
"""
assert isinstance(value, unicode... | [
"def",
"pack_unicode",
"(",
"cls",
",",
"value",
",",
"charset",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"strict\"",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"unicode",
")",
"try",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"charset",
... | Pack string field
<field> ::= <int32_varint><data>
:param value: string to be packed
:type value: unicode
:return: packed value
:rtype: bytes | [
"Pack",
"string",
"field",
"<field",
">",
"::",
"=",
"<int32_varint",
">",
"<data",
">"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L212-L231 |
zlobspb/txtarantool | txtarantool.py | Request.pack_field | def pack_field(self, value):
"""
Pack single field (string or integer value)
<field> ::= <int32_varint><data>
:param value: value to be packed
:type value: bytes, str, int or long
:return: packed value
:rtype: bytes
"""
if isinstance(value, str):... | python | def pack_field(self, value):
"""
Pack single field (string or integer value)
<field> ::= <int32_varint><data>
:param value: value to be packed
:type value: bytes, str, int or long
:return: packed value
:rtype: bytes
"""
if isinstance(value, str):... | [
"def",
"pack_field",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"self",
".",
"pack_str",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"return",
"self",
".... | Pack single field (string or integer value)
<field> ::= <int32_varint><data>
:param value: value to be packed
:type value: bytes, str, int or long
:return: packed value
:rtype: bytes | [
"Pack",
"single",
"field",
"(",
"string",
"or",
"integer",
"value",
")",
"<field",
">",
"::",
"=",
"<int32_varint",
">",
"<data",
">"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L233-L253 |
zlobspb/txtarantool | txtarantool.py | Request.pack_tuple | def pack_tuple(self, values):
"""
Pack tuple of values
<tuple> ::= <cardinality><field>+
:param value: tuple to be packed
:type value: tuple of scalar values (bytes, str or int)
:return: packed tuple
:rtype: bytes
"""
assert isinstance(values, (t... | python | def pack_tuple(self, values):
"""
Pack tuple of values
<tuple> ::= <cardinality><field>+
:param value: tuple to be packed
:type value: tuple of scalar values (bytes, str or int)
:return: packed tuple
:rtype: bytes
"""
assert isinstance(values, (t... | [
"def",
"pack_tuple",
"(",
"self",
",",
"values",
")",
":",
"assert",
"isinstance",
"(",
"values",
",",
"(",
"tuple",
",",
"list",
")",
")",
"cardinality",
"=",
"[",
"struct_L",
".",
"pack",
"(",
"len",
"(",
"values",
")",
")",
"]",
"packed_items",
"=... | Pack tuple of values
<tuple> ::= <cardinality><field>+
:param value: tuple to be packed
:type value: tuple of scalar values (bytes, str or int)
:return: packed tuple
:rtype: bytes | [
"Pack",
"tuple",
"of",
"values",
"<tuple",
">",
"::",
"=",
"<cardinality",
">",
"<field",
">",
"+"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L255-L269 |
zlobspb/txtarantool | txtarantool.py | Response._unpack_int_base128 | def _unpack_int_base128(varint, offset):
"""Implement Perl unpack's 'w' option, aka base 128 decoding."""
res = ord(varint[offset])
if ord(varint[offset]) >= 0x80:
offset += 1
res = ((res - 0x80) << 7) + ord(varint[offset])
if ord(varint[offset]) >= 0x80:
... | python | def _unpack_int_base128(varint, offset):
"""Implement Perl unpack's 'w' option, aka base 128 decoding."""
res = ord(varint[offset])
if ord(varint[offset]) >= 0x80:
offset += 1
res = ((res - 0x80) << 7) + ord(varint[offset])
if ord(varint[offset]) >= 0x80:
... | [
"def",
"_unpack_int_base128",
"(",
"varint",
",",
"offset",
")",
":",
"res",
"=",
"ord",
"(",
"varint",
"[",
"offset",
"]",
")",
"if",
"ord",
"(",
"varint",
"[",
"offset",
"]",
")",
">=",
"0x80",
":",
"offset",
"+=",
"1",
"res",
"=",
"(",
"(",
"r... | Implement Perl unpack's 'w' option, aka base 128 decoding. | [
"Implement",
"Perl",
"unpack",
"s",
"w",
"option",
"aka",
"base",
"128",
"decoding",
"."
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L548-L563 |
zlobspb/txtarantool | txtarantool.py | Response._unpack_tuple | def _unpack_tuple(self, buff):
"""
Unpacks the tuple from byte buffer
<tuple> ::= <cardinality><field>+
:param buff: byte array of the form <cardinality><field>+
:type buff: ctypes buffer or bytes
:return: tuple of unpacked values
:rtype: tuple
"""
... | python | def _unpack_tuple(self, buff):
"""
Unpacks the tuple from byte buffer
<tuple> ::= <cardinality><field>+
:param buff: byte array of the form <cardinality><field>+
:type buff: ctypes buffer or bytes
:return: tuple of unpacked values
:rtype: tuple
"""
... | [
"def",
"_unpack_tuple",
"(",
"self",
",",
"buff",
")",
":",
"cardinality",
"=",
"struct_L",
".",
"unpack_from",
"(",
"buff",
")",
"[",
"0",
"]",
"_tuple",
"=",
"[",
"''",
"]",
"*",
"cardinality",
"offset",
"=",
"4",
"# The first 4 bytes in the response body ... | Unpacks the tuple from byte buffer
<tuple> ::= <cardinality><field>+
:param buff: byte array of the form <cardinality><field>+
:type buff: ctypes buffer or bytes
:return: tuple of unpacked values
:rtype: tuple | [
"Unpacks",
"the",
"tuple",
"from",
"byte",
"buffer",
"<tuple",
">",
"::",
"=",
"<cardinality",
">",
"<field",
">",
"+"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L565-L585 |
zlobspb/txtarantool | txtarantool.py | Response._unpack_body | def _unpack_body(self, buff):
"""
Parse the response body.
After body unpacking its data available as python list of tuples
For each request type the response body has the same format:
<insert_response_body> ::= <count> | <count><fq_tuple>
<update_response_body> ::= <cou... | python | def _unpack_body(self, buff):
"""
Parse the response body.
After body unpacking its data available as python list of tuples
For each request type the response body has the same format:
<insert_response_body> ::= <count> | <count><fq_tuple>
<update_response_body> ::= <cou... | [
"def",
"_unpack_body",
"(",
"self",
",",
"buff",
")",
":",
"# Unpack <return_code> and <count> (how many records affected or selected)",
"self",
".",
"_return_code",
"=",
"struct_L",
".",
"unpack_from",
"(",
"buff",
",",
"offset",
"=",
"0",
")",
"[",
"0",
"]",
"# ... | Parse the response body.
After body unpacking its data available as python list of tuples
For each request type the response body has the same format:
<insert_response_body> ::= <count> | <count><fq_tuple>
<update_response_body> ::= <count> | <count><fq_tuple>
<delete_response_b... | [
"Parse",
"the",
"response",
"body",
".",
"After",
"body",
"unpacking",
"its",
"data",
"available",
"as",
"python",
"list",
"of",
"tuples"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L587-L639 |
zlobspb/txtarantool | txtarantool.py | Response._cast_field | def _cast_field(self, cast_to, value):
"""
Convert field type from raw bytes to native python type
:param cast_to: native python type to cast to
:type cast_to: a type object (one of bytes, int, unicode (str for py3k))
:param value: raw value from the database
:type value... | python | def _cast_field(self, cast_to, value):
"""
Convert field type from raw bytes to native python type
:param cast_to: native python type to cast to
:type cast_to: a type object (one of bytes, int, unicode (str for py3k))
:param value: raw value from the database
:type value... | [
"def",
"_cast_field",
"(",
"self",
",",
"cast_to",
",",
"value",
")",
":",
"if",
"cast_to",
"in",
"(",
"int",
",",
"long",
",",
"str",
")",
":",
"return",
"cast_to",
"(",
"value",
")",
"elif",
"cast_to",
"==",
"unicode",
":",
"try",
":",
"value",
"... | Convert field type from raw bytes to native python type
:param cast_to: native python type to cast to
:type cast_to: a type object (one of bytes, int, unicode (str for py3k))
:param value: raw value from the database
:type value: bytes
:return: converted value
:rtype: v... | [
"Convert",
"field",
"type",
"from",
"raw",
"bytes",
"to",
"native",
"python",
"type"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L686-L710 |
zlobspb/txtarantool | txtarantool.py | Response._cast_tuple | def _cast_tuple(self, values):
"""
Convert values of the tuple from raw bytes to native python types
:param values: tuple of the raw database values
:type value: tuple of bytes
:return: converted tuple value
:rtype: value of native python types (bytes, int, unicode (or ... | python | def _cast_tuple(self, values):
"""
Convert values of the tuple from raw bytes to native python types
:param values: tuple of the raw database values
:type value: tuple of bytes
:return: converted tuple value
:rtype: value of native python types (bytes, int, unicode (or ... | [
"def",
"_cast_tuple",
"(",
"self",
",",
"values",
")",
":",
"result",
"=",
"[",
"]",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"values",
")",
":",
"if",
"i",
"<",
"len",
"(",
"self",
".",
"field_types",
")",
":",
"result",
".",
"append",
... | Convert values of the tuple from raw bytes to native python types
:param values: tuple of the raw database values
:type value: tuple of bytes
:return: converted tuple value
:rtype: value of native python types (bytes, int, unicode (or str for py3k)) | [
"Convert",
"values",
"of",
"the",
"tuple",
"from",
"raw",
"bytes",
"to",
"native",
"python",
"types"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L712-L729 |
zlobspb/txtarantool | txtarantool.py | TarantoolProtocol.ping | def ping(self):
"""
send ping packet to tarantool server and receive response with empty body
"""
d = self.replyQueue.get_ping()
packet = RequestPing(self.charset, self.errors)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, self.charse... | python | def ping(self):
"""
send ping packet to tarantool server and receive response with empty body
"""
d = self.replyQueue.get_ping()
packet = RequestPing(self.charset, self.errors)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, self.charse... | [
"def",
"ping",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"replyQueue",
".",
"get_ping",
"(",
")",
"packet",
"=",
"RequestPing",
"(",
"self",
".",
"charset",
",",
"self",
".",
"errors",
")",
"self",
".",
"transport",
".",
"write",
"(",
"bytes",
... | send ping packet to tarantool server and receive response with empty body | [
"send",
"ping",
"packet",
"to",
"tarantool",
"server",
"and",
"receive",
"response",
"with",
"empty",
"body"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L865-L872 |
zlobspb/txtarantool | txtarantool.py | TarantoolProtocol.insert | def insert(self, space_no, *args):
"""
insert tuple, if primary key exists server will return error
"""
d = self.replyQueue.get()
packet = RequestInsert(self.charset, self.errors, d._ipro_request_id, space_no, Request.TNT_FLAG_ADD, *args)
self.transport.write(bytes(packet... | python | def insert(self, space_no, *args):
"""
insert tuple, if primary key exists server will return error
"""
d = self.replyQueue.get()
packet = RequestInsert(self.charset, self.errors, d._ipro_request_id, space_no, Request.TNT_FLAG_ADD, *args)
self.transport.write(bytes(packet... | [
"def",
"insert",
"(",
"self",
",",
"space_no",
",",
"*",
"args",
")",
":",
"d",
"=",
"self",
".",
"replyQueue",
".",
"get",
"(",
")",
"packet",
"=",
"RequestInsert",
"(",
"self",
".",
"charset",
",",
"self",
".",
"errors",
",",
"d",
".",
"_ipro_req... | insert tuple, if primary key exists server will return error | [
"insert",
"tuple",
"if",
"primary",
"key",
"exists",
"server",
"will",
"return",
"error"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L874-L881 |
zlobspb/txtarantool | txtarantool.py | TarantoolProtocol.select | def select(self, space_no, index_no, field_types, *args):
"""
select tuple(s)
"""
d = self.replyQueue.get()
packet = RequestSelect(self.charset, self.errors, d._ipro_request_id, space_no, index_no, 0, 0xffffffff, *args)
self.transport.write(bytes(packet))
return d... | python | def select(self, space_no, index_no, field_types, *args):
"""
select tuple(s)
"""
d = self.replyQueue.get()
packet = RequestSelect(self.charset, self.errors, d._ipro_request_id, space_no, index_no, 0, 0xffffffff, *args)
self.transport.write(bytes(packet))
return d... | [
"def",
"select",
"(",
"self",
",",
"space_no",
",",
"index_no",
",",
"field_types",
",",
"*",
"args",
")",
":",
"d",
"=",
"self",
".",
"replyQueue",
".",
"get",
"(",
")",
"packet",
"=",
"RequestSelect",
"(",
"self",
".",
"charset",
",",
"self",
".",
... | select tuple(s) | [
"select",
"tuple",
"(",
"s",
")"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L893-L900 |
zlobspb/txtarantool | txtarantool.py | TarantoolProtocol.update | def update(self, space_no, key_tuple, op_list):
"""
send update command(s)
"""
d = self.replyQueue.get()
packet = RequestUpdate(self.charset, self.errors, d._ipro_request_id, space_no, 0, key_tuple, op_list)
self.transport.write(bytes(packet))
return d.addCallback... | python | def update(self, space_no, key_tuple, op_list):
"""
send update command(s)
"""
d = self.replyQueue.get()
packet = RequestUpdate(self.charset, self.errors, d._ipro_request_id, space_no, 0, key_tuple, op_list)
self.transport.write(bytes(packet))
return d.addCallback... | [
"def",
"update",
"(",
"self",
",",
"space_no",
",",
"key_tuple",
",",
"op_list",
")",
":",
"d",
"=",
"self",
".",
"replyQueue",
".",
"get",
"(",
")",
"packet",
"=",
"RequestUpdate",
"(",
"self",
".",
"charset",
",",
"self",
".",
"errors",
",",
"d",
... | send update command(s) | [
"send",
"update",
"command",
"(",
"s",
")"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L911-L918 |
zlobspb/txtarantool | txtarantool.py | TarantoolProtocol.update_ret | def update_ret(self, space_no, field_types, key_tuple, op_list):
"""
send update command(s), updated tuple(s) is(are) sent back
"""
d = self.replyQueue.get()
packet = RequestUpdate(self.charset, self.errors, d._ipro_request_id,
space_no, Request.TNT... | python | def update_ret(self, space_no, field_types, key_tuple, op_list):
"""
send update command(s), updated tuple(s) is(are) sent back
"""
d = self.replyQueue.get()
packet = RequestUpdate(self.charset, self.errors, d._ipro_request_id,
space_no, Request.TNT... | [
"def",
"update_ret",
"(",
"self",
",",
"space_no",
",",
"field_types",
",",
"key_tuple",
",",
"op_list",
")",
":",
"d",
"=",
"self",
".",
"replyQueue",
".",
"get",
"(",
")",
"packet",
"=",
"RequestUpdate",
"(",
"self",
".",
"charset",
",",
"self",
".",... | send update command(s), updated tuple(s) is(are) sent back | [
"send",
"update",
"command",
"(",
"s",
")",
"updated",
"tuple",
"(",
"s",
")",
"is",
"(",
"are",
")",
"sent",
"back"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L920-L928 |
zlobspb/txtarantool | txtarantool.py | TarantoolProtocol.delete | def delete(self, space_no, *args):
"""
delete tuple by primary key
"""
d = self.replyQueue.get()
packet = RequestDelete(self.charset, self.errors, d._ipro_request_id, space_no, 0, *args)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, s... | python | def delete(self, space_no, *args):
"""
delete tuple by primary key
"""
d = self.replyQueue.get()
packet = RequestDelete(self.charset, self.errors, d._ipro_request_id, space_no, 0, *args)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, s... | [
"def",
"delete",
"(",
"self",
",",
"space_no",
",",
"*",
"args",
")",
":",
"d",
"=",
"self",
".",
"replyQueue",
".",
"get",
"(",
")",
"packet",
"=",
"RequestDelete",
"(",
"self",
".",
"charset",
",",
"self",
".",
"errors",
",",
"d",
".",
"_ipro_req... | delete tuple by primary key | [
"delete",
"tuple",
"by",
"primary",
"key"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L930-L937 |
zlobspb/txtarantool | txtarantool.py | TarantoolProtocol.call | def call(self, proc_name, field_types, *args):
"""
call server procedure
"""
d = self.replyQueue.get()
packet = RequestCall(self.charset, self.errors, d._ipro_request_id, proc_name, 0, *args)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_rep... | python | def call(self, proc_name, field_types, *args):
"""
call server procedure
"""
d = self.replyQueue.get()
packet = RequestCall(self.charset, self.errors, d._ipro_request_id, proc_name, 0, *args)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_rep... | [
"def",
"call",
"(",
"self",
",",
"proc_name",
",",
"field_types",
",",
"*",
"args",
")",
":",
"d",
"=",
"self",
".",
"replyQueue",
".",
"get",
"(",
")",
"packet",
"=",
"RequestCall",
"(",
"self",
".",
"charset",
",",
"self",
".",
"errors",
",",
"d"... | call server procedure | [
"call",
"server",
"procedure"
] | train | https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L985-L992 |
lukaszb/porunga | examples/fibs/fibs.py | fibs | def fibs(n, m):
"""
Yields Fibonacci numbers starting from ``n`` and ending at ``m``.
"""
a = b = 1
for x in range(3, m + 1):
a, b = b, a + b
if x >= n:
yield b | python | def fibs(n, m):
"""
Yields Fibonacci numbers starting from ``n`` and ending at ``m``.
"""
a = b = 1
for x in range(3, m + 1):
a, b = b, a + b
if x >= n:
yield b | [
"def",
"fibs",
"(",
"n",
",",
"m",
")",
":",
"a",
"=",
"b",
"=",
"1",
"for",
"x",
"in",
"range",
"(",
"3",
",",
"m",
"+",
"1",
")",
":",
"a",
",",
"b",
"=",
"b",
",",
"a",
"+",
"b",
"if",
"x",
">=",
"n",
":",
"yield",
"b"
] | Yields Fibonacci numbers starting from ``n`` and ending at ``m``. | [
"Yields",
"Fibonacci",
"numbers",
"starting",
"from",
"n",
"and",
"ending",
"at",
"m",
"."
] | train | https://github.com/lukaszb/porunga/blob/13177ff9bc654ac25cf09def6b526eb38e40e483/examples/fibs/fibs.py#L6-L14 |
emencia/emencia-django-countries | emencia/django/countries/migrations/0002_auto_load_initial_data.py | unload_fixture | def unload_fixture(apps, schema_editor):
"""
Brutally deleting all 'Country' model entries for reversing operation
"""
appmodel = apps.get_model(APP_LABEL, COUNTRY_MODELNAME)
appmodel.objects.all().delete() | python | def unload_fixture(apps, schema_editor):
"""
Brutally deleting all 'Country' model entries for reversing operation
"""
appmodel = apps.get_model(APP_LABEL, COUNTRY_MODELNAME)
appmodel.objects.all().delete() | [
"def",
"unload_fixture",
"(",
"apps",
",",
"schema_editor",
")",
":",
"appmodel",
"=",
"apps",
".",
"get_model",
"(",
"APP_LABEL",
",",
"COUNTRY_MODELNAME",
")",
"appmodel",
".",
"objects",
".",
"all",
"(",
")",
".",
"delete",
"(",
")"
] | Brutally deleting all 'Country' model entries for reversing operation | [
"Brutally",
"deleting",
"all",
"Country",
"model",
"entries",
"for",
"reversing",
"operation"
] | train | https://github.com/emencia/emencia-django-countries/blob/5ae8719f4b43caeca2c69c9e37e6d6bc5d7b0290/emencia/django/countries/migrations/0002_auto_load_initial_data.py#L20-L25 |
picleslivre/plumber | plumber.py | precondition | def precondition(precond):
"""
Runs the callable responsible for making some assertions
about the data structure expected for the transformation.
If the precondition is not achieved, a UnmetPrecondition
exception must be raised, and then the transformation pipe
is bypassed.
"""
def deco... | python | def precondition(precond):
"""
Runs the callable responsible for making some assertions
about the data structure expected for the transformation.
If the precondition is not achieved, a UnmetPrecondition
exception must be raised, and then the transformation pipe
is bypassed.
"""
def deco... | [
"def",
"precondition",
"(",
"precond",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"\"\"\"`f` can be a reference to a method or function. In\n both cases the `data` is expected to be passed as the\n first positional argument (obviously respecting the\n `self` argum... | Runs the callable responsible for making some assertions
about the data structure expected for the transformation.
If the precondition is not achieved, a UnmetPrecondition
exception must be raised, and then the transformation pipe
is bypassed. | [
"Runs",
"the",
"callable",
"responsible",
"for",
"making",
"some",
"assertions",
"about",
"the",
"data",
"structure",
"expected",
"for",
"the",
"transformation",
"."
] | train | https://github.com/picleslivre/plumber/blob/f5019ef20679b3e9a31c6c84e4f4529d72dc8db9/plumber.py#L76-L111 |
picleslivre/plumber | plumber.py | Pipeline.run | def run(self, data, rewrap=False, prefetch=0):
"""
Wires the pipeline and returns a lazy object of
the transformed data.
:param data: must be an iterable, where a full document
must be returned for each loop
:param rewrap: (optional) is a bool that indicates the need to... | python | def run(self, data, rewrap=False, prefetch=0):
"""
Wires the pipeline and returns a lazy object of
the transformed data.
:param data: must be an iterable, where a full document
must be returned for each loop
:param rewrap: (optional) is a bool that indicates the need to... | [
"def",
"run",
"(",
"self",
",",
"data",
",",
"rewrap",
"=",
"False",
",",
"prefetch",
"=",
"0",
")",
":",
"if",
"rewrap",
":",
"data",
"=",
"[",
"data",
"]",
"for",
"_filter",
"in",
"self",
".",
"_filters",
":",
"_filter",
".",
"feed",
"(",
"data... | Wires the pipeline and returns a lazy object of
the transformed data.
:param data: must be an iterable, where a full document
must be returned for each loop
:param rewrap: (optional) is a bool that indicates the need to rewrap
data in cases where iterating over it produces unde... | [
"Wires",
"the",
"pipeline",
"and",
"returns",
"a",
"lazy",
"object",
"of",
"the",
"transformed",
"data",
"."
] | train | https://github.com/picleslivre/plumber/blob/f5019ef20679b3e9a31c6c84e4f4529d72dc8db9/plumber.py#L203-L229 |
dillonhicks/rekt | rekt/utils.py | camel_case_to_snake_case | def camel_case_to_snake_case(name):
"""
HelloWorld -> hello_world
"""
s1 = _FIRST_CAP_RE.sub(r'\1_\2', name)
return _ALL_CAP_RE.sub(r'\1_\2', s1).lower() | python | def camel_case_to_snake_case(name):
"""
HelloWorld -> hello_world
"""
s1 = _FIRST_CAP_RE.sub(r'\1_\2', name)
return _ALL_CAP_RE.sub(r'\1_\2', s1).lower() | [
"def",
"camel_case_to_snake_case",
"(",
"name",
")",
":",
"s1",
"=",
"_FIRST_CAP_RE",
".",
"sub",
"(",
"r'\\1_\\2'",
",",
"name",
")",
"return",
"_ALL_CAP_RE",
".",
"sub",
"(",
"r'\\1_\\2'",
",",
"s1",
")",
".",
"lower",
"(",
")"
] | HelloWorld -> hello_world | [
"HelloWorld",
"-",
">",
"hello_world"
] | train | https://github.com/dillonhicks/rekt/blob/3848b272726c78214cb96b906f9b9f289497f27e/rekt/utils.py#L33-L38 |
dillonhicks/rekt | rekt/utils.py | load_builtin_config | def load_builtin_config(name, module_name=__name__, specs_path=specs.__path__):
"""
Uses package info magic to find the resource file located in the specs
submodule.
"""
config_path = Path(next(iter(specs_path)))
config_path = config_path / PurePath(resource_filename(module_name, name + '.yaml')... | python | def load_builtin_config(name, module_name=__name__, specs_path=specs.__path__):
"""
Uses package info magic to find the resource file located in the specs
submodule.
"""
config_path = Path(next(iter(specs_path)))
config_path = config_path / PurePath(resource_filename(module_name, name + '.yaml')... | [
"def",
"load_builtin_config",
"(",
"name",
",",
"module_name",
"=",
"__name__",
",",
"specs_path",
"=",
"specs",
".",
"__path__",
")",
":",
"config_path",
"=",
"Path",
"(",
"next",
"(",
"iter",
"(",
"specs_path",
")",
")",
")",
"config_path",
"=",
"config_... | Uses package info magic to find the resource file located in the specs
submodule. | [
"Uses",
"package",
"info",
"magic",
"to",
"find",
"the",
"resource",
"file",
"located",
"in",
"the",
"specs",
"submodule",
"."
] | train | https://github.com/dillonhicks/rekt/blob/3848b272726c78214cb96b906f9b9f289497f27e/rekt/utils.py#L47-L54 |
dillonhicks/rekt | rekt/utils.py | load_config | def load_config(path):
"""
Loads a yaml configuration.
:param path: a pathlib Path object pointing to the configuration
"""
with path.open('rb') as fi:
file_bytes = fi.read()
config = yaml.load(file_bytes.decode('utf-8'))
return config | python | def load_config(path):
"""
Loads a yaml configuration.
:param path: a pathlib Path object pointing to the configuration
"""
with path.open('rb') as fi:
file_bytes = fi.read()
config = yaml.load(file_bytes.decode('utf-8'))
return config | [
"def",
"load_config",
"(",
"path",
")",
":",
"with",
"path",
".",
"open",
"(",
"'rb'",
")",
"as",
"fi",
":",
"file_bytes",
"=",
"fi",
".",
"read",
"(",
")",
"config",
"=",
"yaml",
".",
"load",
"(",
"file_bytes",
".",
"decode",
"(",
"'utf-8'",
")",
... | Loads a yaml configuration.
:param path: a pathlib Path object pointing to the configuration | [
"Loads",
"a",
"yaml",
"configuration",
"."
] | train | https://github.com/dillonhicks/rekt/blob/3848b272726c78214cb96b906f9b9f289497f27e/rekt/utils.py#L56-L66 |
dillonhicks/rekt | rekt/utils.py | load_swagger_config | def load_swagger_config(name, base_url, config):
"""
Load a restful service specified by some YAML file at config_path.
:param config_path: A pathlib Path object that points to the yaml
config
:returns: A python module containing a Client class, call factory,
and the definition of each of the... | python | def load_swagger_config(name, base_url, config):
"""
Load a restful service specified by some YAML file at config_path.
:param config_path: A pathlib Path object that points to the yaml
config
:returns: A python module containing a Client class, call factory,
and the definition of each of the... | [
"def",
"load_swagger_config",
"(",
"name",
",",
"base_url",
",",
"config",
")",
":",
"if",
"isinstance",
"(",
"config",
",",
"collections",
".",
"abc",
".",
"Mapping",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"config",
",",
"str",
")",
":",
"with",
... | Load a restful service specified by some YAML file at config_path.
:param config_path: A pathlib Path object that points to the yaml
config
:returns: A python module containing a Client class, call factory,
and the definition of each of the APIs defined by the config. | [
"Load",
"a",
"restful",
"service",
"specified",
"by",
"some",
"YAML",
"file",
"at",
"config_path",
"."
] | train | https://github.com/dillonhicks/rekt/blob/3848b272726c78214cb96b906f9b9f289497f27e/rekt/utils.py#L92-L136 |
TakesxiSximada/jumon | src/jumon/__init__.py | mkdir | def mkdir(path, parents=False):
"""
parents: no error if existing, make parent directories as needed
"""
func = os.makedirs if parents else os.mkdir
try:
return func(path)
except:
if not parents:
raise | python | def mkdir(path, parents=False):
"""
parents: no error if existing, make parent directories as needed
"""
func = os.makedirs if parents else os.mkdir
try:
return func(path)
except:
if not parents:
raise | [
"def",
"mkdir",
"(",
"path",
",",
"parents",
"=",
"False",
")",
":",
"func",
"=",
"os",
".",
"makedirs",
"if",
"parents",
"else",
"os",
".",
"mkdir",
"try",
":",
"return",
"func",
"(",
"path",
")",
"except",
":",
"if",
"not",
"parents",
":",
"raise... | parents: no error if existing, make parent directories as needed | [
"parents",
":",
"no",
"error",
"if",
"existing",
"make",
"parent",
"directories",
"as",
"needed"
] | train | https://github.com/TakesxiSximada/jumon/blob/7b659882bc3d5036588dfbc4c901291be650468e/src/jumon/__init__.py#L152-L161 |
TakesxiSximada/jumon | src/jumon/__init__.py | Shell.sudo | def sudo(cls, line, *args, **kwds):
"""
duplicated
"""
sudo_user = Env.get(Env.JUMON_SUDO)
if sudo_user:
line = 'sudo -u {} {}'.format(sudo_user, line)
return cls.call(line, *args, **kwds) | python | def sudo(cls, line, *args, **kwds):
"""
duplicated
"""
sudo_user = Env.get(Env.JUMON_SUDO)
if sudo_user:
line = 'sudo -u {} {}'.format(sudo_user, line)
return cls.call(line, *args, **kwds) | [
"def",
"sudo",
"(",
"cls",
",",
"line",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"sudo_user",
"=",
"Env",
".",
"get",
"(",
"Env",
".",
"JUMON_SUDO",
")",
"if",
"sudo_user",
":",
"line",
"=",
"'sudo -u {} {}'",
".",
"format",
"(",
"sudo_us... | duplicated | [
"duplicated"
] | train | https://github.com/TakesxiSximada/jumon/blob/7b659882bc3d5036588dfbc4c901291be650468e/src/jumon/__init__.py#L128-L135 |
TakesxiSximada/jumon | src/jumon/__init__.py | Shell.system_old | def system_old(cls, line):
"""
duplicated
"""
print('')
print('$ {}'.format(line))
return os.system(line) | python | def system_old(cls, line):
"""
duplicated
"""
print('')
print('$ {}'.format(line))
return os.system(line) | [
"def",
"system_old",
"(",
"cls",
",",
"line",
")",
":",
"print",
"(",
"''",
")",
"print",
"(",
"'$ {}'",
".",
"format",
"(",
"line",
")",
")",
"return",
"os",
".",
"system",
"(",
"line",
")"
] | duplicated | [
"duplicated"
] | train | https://github.com/TakesxiSximada/jumon/blob/7b659882bc3d5036588dfbc4c901291be650468e/src/jumon/__init__.py#L138-L144 |
TakesxiSximada/jumon | src/jumon/__init__.py | TransparentOptionParser._process_args | def _process_args(self, largs, rargs, values):
"""_process_args(largs : [string],
rargs : [string],
values : Values)
Process command-line arguments and populate 'values', consuming
options and arguments from 'rargs'. If 'allow_interspersed_args' is
fals... | python | def _process_args(self, largs, rargs, values):
"""_process_args(largs : [string],
rargs : [string],
values : Values)
Process command-line arguments and populate 'values', consuming
options and arguments from 'rargs'. If 'allow_interspersed_args' is
fals... | [
"def",
"_process_args",
"(",
"self",
",",
"largs",
",",
"rargs",
",",
"values",
")",
":",
"def",
"_through_option",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"\"\"\"new function\"\"\"",
"try",
":",
"func",
"(",
"*",
"args",
",",
... | _process_args(largs : [string],
rargs : [string],
values : Values)
Process command-line arguments and populate 'values', consuming
options and arguments from 'rargs'. If 'allow_interspersed_args' is
false, stop at the first non-option argument. If true, accumu... | [
"_process_args",
"(",
"largs",
":",
"[",
"string",
"]",
"rargs",
":",
"[",
"string",
"]",
"values",
":",
"Values",
")"
] | train | https://github.com/TakesxiSximada/jumon/blob/7b659882bc3d5036588dfbc4c901291be650468e/src/jumon/__init__.py#L180-L218 |
EwilDawe/typy | typy/mouse.py | move_line | def move_line(x, y, speed = 1):
"""
Moves the cursor in a straight line to (x, y) at a certain speed
:param x: target x-ordinate
:param y: target y-ordinate
:param speed: pixel traversal rate
:return: None
"""
_x, _y = win32api.GetCursorPos()
if x - _x:
m = (y - _y) / (x - ... | python | def move_line(x, y, speed = 1):
"""
Moves the cursor in a straight line to (x, y) at a certain speed
:param x: target x-ordinate
:param y: target y-ordinate
:param speed: pixel traversal rate
:return: None
"""
_x, _y = win32api.GetCursorPos()
if x - _x:
m = (y - _y) / (x - ... | [
"def",
"move_line",
"(",
"x",
",",
"y",
",",
"speed",
"=",
"1",
")",
":",
"_x",
",",
"_y",
"=",
"win32api",
".",
"GetCursorPos",
"(",
")",
"if",
"x",
"-",
"_x",
":",
"m",
"=",
"(",
"y",
"-",
"_y",
")",
"/",
"(",
"x",
"-",
"_x",
")",
"c",
... | Moves the cursor in a straight line to (x, y) at a certain speed
:param x: target x-ordinate
:param y: target y-ordinate
:param speed: pixel traversal rate
:return: None | [
"Moves",
"the",
"cursor",
"in",
"a",
"straight",
"line",
"to",
"(",
"x",
"y",
")",
"at",
"a",
"certain",
"speed"
] | train | https://github.com/EwilDawe/typy/blob/0349e7176567a4dbef318e75d9b3d6868950a1a9/typy/mouse.py#L18-L40 |
EwilDawe/typy | typy/mouse.py | move_arc | def move_arc(x, y, r, speed = 1, orientation = True):
# WARNING: This function currently contains inaccuracy likely due to the rounding of trigonometric functions
"""
Moves the cursor in an arc of radius r to (x, y) at a certain speed
:param x: target x-ordinate
:param y: target y-ordinate
:par... | python | def move_arc(x, y, r, speed = 1, orientation = True):
# WARNING: This function currently contains inaccuracy likely due to the rounding of trigonometric functions
"""
Moves the cursor in an arc of radius r to (x, y) at a certain speed
:param x: target x-ordinate
:param y: target y-ordinate
:par... | [
"def",
"move_arc",
"(",
"x",
",",
"y",
",",
"r",
",",
"speed",
"=",
"1",
",",
"orientation",
"=",
"True",
")",
":",
"# WARNING: This function currently contains inaccuracy likely due to the rounding of trigonometric functions",
"_x",
",",
"_y",
"=",
"win32api",
".",
... | Moves the cursor in an arc of radius r to (x, y) at a certain speed
:param x: target x-ordinate
:param y: target y-ordinate
:param r: radius
:param speed: pixel traversal rate
:param orientation: direction of arc
:return: None | [
"Moves",
"the",
"cursor",
"in",
"an",
"arc",
"of",
"radius",
"r",
"to",
"(",
"x",
"y",
")",
"at",
"a",
"certain",
"speed"
] | train | https://github.com/EwilDawe/typy/blob/0349e7176567a4dbef318e75d9b3d6868950a1a9/typy/mouse.py#L43-L69 |
EwilDawe/typy | typy/mouse.py | drag | def drag(*args, function = move):
"""
Drags the mouse along a specified path
:param args: list of arguments passed to function
:param function: path to traverse
:return: None
"""
x, y = win32api.GetCursorPos()
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
function... | python | def drag(*args, function = move):
"""
Drags the mouse along a specified path
:param args: list of arguments passed to function
:param function: path to traverse
:return: None
"""
x, y = win32api.GetCursorPos()
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
function... | [
"def",
"drag",
"(",
"*",
"args",
",",
"function",
"=",
"move",
")",
":",
"x",
",",
"y",
"=",
"win32api",
".",
"GetCursorPos",
"(",
")",
"win32api",
".",
"mouse_event",
"(",
"win32con",
".",
"MOUSEEVENTF_LEFTDOWN",
",",
"x",
",",
"y",
",",
"0",
",",
... | Drags the mouse along a specified path
:param args: list of arguments passed to function
:param function: path to traverse
:return: None | [
"Drags",
"the",
"mouse",
"along",
"a",
"specified",
"path"
] | train | https://github.com/EwilDawe/typy/blob/0349e7176567a4dbef318e75d9b3d6868950a1a9/typy/mouse.py#L72-L85 |
EwilDawe/typy | typy/mouse.py | click_left | def click_left(x = None, y = None, hold_time = 0):
"""
Simulates a mouse left click on pixel (x,y) if x and y are provided
If x and y are not passed to this function, a mouse click is simulated at the current (x,y)
:param x: target x-ordinate
:param y: target y-ordinate
:param hold_time: length... | python | def click_left(x = None, y = None, hold_time = 0):
"""
Simulates a mouse left click on pixel (x,y) if x and y are provided
If x and y are not passed to this function, a mouse click is simulated at the current (x,y)
:param x: target x-ordinate
:param y: target y-ordinate
:param hold_time: length... | [
"def",
"click_left",
"(",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"hold_time",
"=",
"0",
")",
":",
"if",
"not",
"x",
"or",
"not",
"y",
":",
"cursor",
"=",
"win32api",
".",
"GetCursorPos",
"(",
")",
"if",
"not",
"x",
":",
"x",
"=",
"cursor... | Simulates a mouse left click on pixel (x,y) if x and y are provided
If x and y are not passed to this function, a mouse click is simulated at the current (x,y)
:param x: target x-ordinate
:param y: target y-ordinate
:param hold_time: length of time to hold the mouse's left button
:return: None | [
"Simulates",
"a",
"mouse",
"left",
"click",
"on",
"pixel",
"(",
"x",
"y",
")",
"if",
"x",
"and",
"y",
"are",
"provided",
"If",
"x",
"and",
"y",
"are",
"not",
"passed",
"to",
"this",
"function",
"a",
"mouse",
"click",
"is",
"simulated",
"at",
"the",
... | train | https://github.com/EwilDawe/typy/blob/0349e7176567a4dbef318e75d9b3d6868950a1a9/typy/mouse.py#L88-L108 |
EwilDawe/typy | typy/mouse.py | click_right | def click_right(x = None, y = None, hold_time = 0):
"""
Simulates a mouse right click on pixel (x,y) if x and y are provided
If x and y are not passed to this function, a mouse click is simulated at the current (x,y)
:param x: target x-ordinate
:param y: target y-ordinate
:param hold_time: leng... | python | def click_right(x = None, y = None, hold_time = 0):
"""
Simulates a mouse right click on pixel (x,y) if x and y are provided
If x and y are not passed to this function, a mouse click is simulated at the current (x,y)
:param x: target x-ordinate
:param y: target y-ordinate
:param hold_time: leng... | [
"def",
"click_right",
"(",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"hold_time",
"=",
"0",
")",
":",
"if",
"not",
"x",
"or",
"not",
"y",
":",
"cursor",
"=",
"win32api",
".",
"GetCursorPos",
"(",
")",
"if",
"not",
"x",
":",
"x",
"=",
"curso... | Simulates a mouse right click on pixel (x,y) if x and y are provided
If x and y are not passed to this function, a mouse click is simulated at the current (x,y)
:param x: target x-ordinate
:param y: target y-ordinate
:param hold_time: length of time to hold the mouse's right button
:return: None | [
"Simulates",
"a",
"mouse",
"right",
"click",
"on",
"pixel",
"(",
"x",
"y",
")",
"if",
"x",
"and",
"y",
"are",
"provided",
"If",
"x",
"and",
"y",
"are",
"not",
"passed",
"to",
"this",
"function",
"a",
"mouse",
"click",
"is",
"simulated",
"at",
"the",
... | train | https://github.com/EwilDawe/typy/blob/0349e7176567a4dbef318e75d9b3d6868950a1a9/typy/mouse.py#L111-L131 |
mikerhodes/actionqueues | actionqueues/actionqueue.py | ActionQueue.add | def add(self, action):
"""Add an action to the execution queue."""
self._state_machine.transition_to_add()
self._actions.append(action) | python | def add(self, action):
"""Add an action to the execution queue."""
self._state_machine.transition_to_add()
self._actions.append(action) | [
"def",
"add",
"(",
"self",
",",
"action",
")",
":",
"self",
".",
"_state_machine",
".",
"transition_to_add",
"(",
")",
"self",
".",
"_actions",
".",
"append",
"(",
"action",
")"
] | Add an action to the execution queue. | [
"Add",
"an",
"action",
"to",
"the",
"execution",
"queue",
"."
] | train | https://github.com/mikerhodes/actionqueues/blob/a7a78ab116abe88af95b5315dc9f34d40ce81eb2/actionqueues/actionqueue.py#L22-L25 |
mikerhodes/actionqueues | actionqueues/actionqueue.py | ActionQueue.execute | def execute(self):
"""Execute all actions, throwing an ExecutionException on failure.
Catch the ExecutionException and call rollback() to rollback.
"""
self._state_machine.transition_to_execute()
for action in self._actions:
self._executed_actions.append(action)
... | python | def execute(self):
"""Execute all actions, throwing an ExecutionException on failure.
Catch the ExecutionException and call rollback() to rollback.
"""
self._state_machine.transition_to_execute()
for action in self._actions:
self._executed_actions.append(action)
... | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"_state_machine",
".",
"transition_to_execute",
"(",
")",
"for",
"action",
"in",
"self",
".",
"_actions",
":",
"self",
".",
"_executed_actions",
".",
"append",
"(",
"action",
")",
"self",
".",
"execute_... | Execute all actions, throwing an ExecutionException on failure.
Catch the ExecutionException and call rollback() to rollback. | [
"Execute",
"all",
"actions",
"throwing",
"an",
"ExecutionException",
"on",
"failure",
"."
] | train | https://github.com/mikerhodes/actionqueues/blob/a7a78ab116abe88af95b5315dc9f34d40ce81eb2/actionqueues/actionqueue.py#L27-L36 |
mikerhodes/actionqueues | actionqueues/actionqueue.py | ActionQueue.rollback | def rollback(self):
"""Call rollback on executed actions."""
self._state_machine.transition_to_rollback()
for action in reversed(self._executed_actions):
try:
self.execute_with_retries(action, lambda a: a.rollback())
except: # pylint: disable=bare-except
... | python | def rollback(self):
"""Call rollback on executed actions."""
self._state_machine.transition_to_rollback()
for action in reversed(self._executed_actions):
try:
self.execute_with_retries(action, lambda a: a.rollback())
except: # pylint: disable=bare-except
... | [
"def",
"rollback",
"(",
"self",
")",
":",
"self",
".",
"_state_machine",
".",
"transition_to_rollback",
"(",
")",
"for",
"action",
"in",
"reversed",
"(",
"self",
".",
"_executed_actions",
")",
":",
"try",
":",
"self",
".",
"execute_with_retries",
"(",
"actio... | Call rollback on executed actions. | [
"Call",
"rollback",
"on",
"executed",
"actions",
"."
] | train | https://github.com/mikerhodes/actionqueues/blob/a7a78ab116abe88af95b5315dc9f34d40ce81eb2/actionqueues/actionqueue.py#L38-L46 |
mikerhodes/actionqueues | actionqueues/actionqueue.py | ActionQueue.execute_with_retries | def execute_with_retries(self, action, f):
"""Execute function f with single argument action. Retry if
ActionRetryException is raised.
"""
# Run action until either it succeeds or throws an exception
# that's not an ActionRetryException
retry = True
while retry:
... | python | def execute_with_retries(self, action, f):
"""Execute function f with single argument action. Retry if
ActionRetryException is raised.
"""
# Run action until either it succeeds or throws an exception
# that's not an ActionRetryException
retry = True
while retry:
... | [
"def",
"execute_with_retries",
"(",
"self",
",",
"action",
",",
"f",
")",
":",
"# Run action until either it succeeds or throws an exception",
"# that's not an ActionRetryException",
"retry",
"=",
"True",
"while",
"retry",
":",
"retry",
"=",
"False",
"try",
":",
"f",
... | Execute function f with single argument action. Retry if
ActionRetryException is raised. | [
"Execute",
"function",
"f",
"with",
"single",
"argument",
"action",
".",
"Retry",
"if",
"ActionRetryException",
"is",
"raised",
"."
] | train | https://github.com/mikerhodes/actionqueues/blob/a7a78ab116abe88af95b5315dc9f34d40ce81eb2/actionqueues/actionqueue.py#L48-L61 |
Vito2015/pyextend | pyextend/network/regex.py | email_match | def email_match(string):
"""邮箱地址匹配. 匹配成功返回(email_name, email_server), 否则返回None"""
m = re.match(email_pattern, string)
if m:
# print('Match success: %s' % m.string)
return m.groups()[0], m.groups()[2]
else:
# print('Match failed: %s' % string)
return None | python | def email_match(string):
"""邮箱地址匹配. 匹配成功返回(email_name, email_server), 否则返回None"""
m = re.match(email_pattern, string)
if m:
# print('Match success: %s' % m.string)
return m.groups()[0], m.groups()[2]
else:
# print('Match failed: %s' % string)
return None | [
"def",
"email_match",
"(",
"string",
")",
":",
"m",
"=",
"re",
".",
"match",
"(",
"email_pattern",
",",
"string",
")",
"if",
"m",
":",
"# print('Match success: %s' % m.string)",
"return",
"m",
".",
"groups",
"(",
")",
"[",
"0",
"]",
",",
"m",
".",
"gro... | 邮箱地址匹配. 匹配成功返回(email_name, email_server), 否则返回None | [
"邮箱地址匹配",
".",
"匹配成功返回",
"(",
"email_name",
"email_server",
")",
"否则返回None"
] | train | https://github.com/Vito2015/pyextend/blob/36861dfe1087e437ffe9b5a1da9345c85b4fa4a1/pyextend/network/regex.py#L23-L31 |
shi-cong/PYSTUDY | PYSTUDY/api/google.py | geocode | def geocode(*params):
"""
遗憾的是拥有GFW的存在,导致本代码无法运行和测试。
:param params:
:return:
"""
http = HTTP()
api = 'https://maps.google.com/maps/api/geocode/xml'
headers = {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encodi... | python | def geocode(*params):
"""
遗憾的是拥有GFW的存在,导致本代码无法运行和测试。
:param params:
:return:
"""
http = HTTP()
api = 'https://maps.google.com/maps/api/geocode/xml'
headers = {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encodi... | [
"def",
"geocode",
"(",
"*",
"params",
")",
":",
"http",
"=",
"HTTP",
"(",
")",
"api",
"=",
"'https://maps.google.com/maps/api/geocode/xml'",
"headers",
"=",
"{",
"'Accept'",
":",
"'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'",
",",... | 遗憾的是拥有GFW的存在,导致本代码无法运行和测试。
:param params:
:return: | [
"遗憾的是拥有GFW的存在,导致本代码无法运行和测试。",
":",
"param",
"params",
":",
":",
"return",
":"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/api/google.py#L7-L30 |
minhhh/pelican_git | pelican_git/plugin.py | fetch_git | def fetch_git(repo, filename, branch="master", hash=None):
"""Fetch a gist and return the contents as a string."""
url = git_url(repo, filename, branch, hash)
response = requests.get(url)
if response.status_code != 200:
raise Exception('Got a bad status looking up gist.')
body = response.te... | python | def fetch_git(repo, filename, branch="master", hash=None):
"""Fetch a gist and return the contents as a string."""
url = git_url(repo, filename, branch, hash)
response = requests.get(url)
if response.status_code != 200:
raise Exception('Got a bad status looking up gist.')
body = response.te... | [
"def",
"fetch_git",
"(",
"repo",
",",
"filename",
",",
"branch",
"=",
"\"master\"",
",",
"hash",
"=",
"None",
")",
":",
"url",
"=",
"git_url",
"(",
"repo",
",",
"filename",
",",
"branch",
",",
"hash",
")",
"response",
"=",
"requests",
".",
"get",
"("... | Fetch a gist and return the contents as a string. | [
"Fetch",
"a",
"gist",
"and",
"return",
"the",
"contents",
"as",
"a",
"string",
"."
] | train | https://github.com/minhhh/pelican_git/blob/9e4758adb5c70b95979f1953823a2fcf1c76e50c/pelican_git/plugin.py#L60-L71 |
minhhh/pelican_git | pelican_git/plugin.py | setup_git | def setup_git(pelican):
"""Setup the default settings."""
pelican.settings.setdefault('GIT_CACHE_ENABLED', False)
pelican.settings.setdefault('GIT_CACHE_LOCATION',
'/tmp/git-cache')
# Make sure the cache directory exists
cache_base = pelican.settings.get('GIT_CACHE_L... | python | def setup_git(pelican):
"""Setup the default settings."""
pelican.settings.setdefault('GIT_CACHE_ENABLED', False)
pelican.settings.setdefault('GIT_CACHE_LOCATION',
'/tmp/git-cache')
# Make sure the cache directory exists
cache_base = pelican.settings.get('GIT_CACHE_L... | [
"def",
"setup_git",
"(",
"pelican",
")",
":",
"pelican",
".",
"settings",
".",
"setdefault",
"(",
"'GIT_CACHE_ENABLED'",
",",
"False",
")",
"pelican",
".",
"settings",
".",
"setdefault",
"(",
"'GIT_CACHE_LOCATION'",
",",
"'/tmp/git-cache'",
")",
"# Make sure the c... | Setup the default settings. | [
"Setup",
"the",
"default",
"settings",
"."
] | train | https://github.com/minhhh/pelican_git/blob/9e4758adb5c70b95979f1953823a2fcf1c76e50c/pelican_git/plugin.py#L74-L83 |
minhhh/pelican_git | pelican_git/plugin.py | replace_git_url | def replace_git_url(generator):
"""Replace gist tags in the article content."""
template = g_jinja2.get_template(GIT_TEMPLATE)
should_cache = generator.context.get('GIT_CACHE_ENABLED')
cache_location = generator.context.get('GIT_CACHE_LOCATION')
for article in generator.articles:
for match... | python | def replace_git_url(generator):
"""Replace gist tags in the article content."""
template = g_jinja2.get_template(GIT_TEMPLATE)
should_cache = generator.context.get('GIT_CACHE_ENABLED')
cache_location = generator.context.get('GIT_CACHE_LOCATION')
for article in generator.articles:
for match... | [
"def",
"replace_git_url",
"(",
"generator",
")",
":",
"template",
"=",
"g_jinja2",
".",
"get_template",
"(",
"GIT_TEMPLATE",
")",
"should_cache",
"=",
"generator",
".",
"context",
".",
"get",
"(",
"'GIT_CACHE_ENABLED'",
")",
"cache_location",
"=",
"generator",
"... | Replace gist tags in the article content. | [
"Replace",
"gist",
"tags",
"in",
"the",
"article",
"content",
"."
] | train | https://github.com/minhhh/pelican_git/blob/9e4758adb5c70b95979f1953823a2fcf1c76e50c/pelican_git/plugin.py#L93-L144 |
minhhh/pelican_git | pelican_git/plugin.py | register | def register():
"""Plugin registration."""
from pelican import signals
signals.initialized.connect(setup_git)
signals.article_generator_finalized.connect(replace_git_url) | python | def register():
"""Plugin registration."""
from pelican import signals
signals.initialized.connect(setup_git)
signals.article_generator_finalized.connect(replace_git_url) | [
"def",
"register",
"(",
")",
":",
"from",
"pelican",
"import",
"signals",
"signals",
".",
"initialized",
".",
"connect",
"(",
"setup_git",
")",
"signals",
".",
"article_generator_finalized",
".",
"connect",
"(",
"replace_git_url",
")"
] | Plugin registration. | [
"Plugin",
"registration",
"."
] | train | https://github.com/minhhh/pelican_git/blob/9e4758adb5c70b95979f1953823a2fcf1c76e50c/pelican_git/plugin.py#L147-L153 |
clearclaw/logtool | logtool/logtime.py | time_str | def time_str (time_t, slug = False):
'''Converts floating point number a'la time.time()
using DEFAULT_TIMEFORMAT
'''
return datetime.fromtimestamp (int (time_t)).strftime (
DEFAULT_SLUGFORMAT if slug else DEFAULT_TIMEFORMAT) | python | def time_str (time_t, slug = False):
'''Converts floating point number a'la time.time()
using DEFAULT_TIMEFORMAT
'''
return datetime.fromtimestamp (int (time_t)).strftime (
DEFAULT_SLUGFORMAT if slug else DEFAULT_TIMEFORMAT) | [
"def",
"time_str",
"(",
"time_t",
",",
"slug",
"=",
"False",
")",
":",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"time_t",
")",
")",
".",
"strftime",
"(",
"DEFAULT_SLUGFORMAT",
"if",
"slug",
"else",
"DEFAULT_TIMEFORMAT",
")"
] | Converts floating point number a'la time.time()
using DEFAULT_TIMEFORMAT | [
"Converts",
"floating",
"point",
"number",
"a",
"la",
"time",
".",
"time",
"()",
"using",
"DEFAULT_TIMEFORMAT"
] | train | https://github.com/clearclaw/logtool/blob/e34c9a580538a9a14fec9b4bbab8b8df92ad36e7/logtool/logtime.py#L15-L20 |
clearclaw/logtool | logtool/logtime.py | now | def now (time_t = None, slug = False):
'''Gives current time as tuple (t, t_str) where
t is integer portion from time.time()
t_str string of t using DEFAULT_TIMEFORMAT
'''
if not time_t:
time_t = time ()
time_s = strftime (
DEFAULT_SLUGFORMAT if slug else DEFAULT_TIMEFORMAT,
gmtime (time_t... | python | def now (time_t = None, slug = False):
'''Gives current time as tuple (t, t_str) where
t is integer portion from time.time()
t_str string of t using DEFAULT_TIMEFORMAT
'''
if not time_t:
time_t = time ()
time_s = strftime (
DEFAULT_SLUGFORMAT if slug else DEFAULT_TIMEFORMAT,
gmtime (time_t... | [
"def",
"now",
"(",
"time_t",
"=",
"None",
",",
"slug",
"=",
"False",
")",
":",
"if",
"not",
"time_t",
":",
"time_t",
"=",
"time",
"(",
")",
"time_s",
"=",
"strftime",
"(",
"DEFAULT_SLUGFORMAT",
"if",
"slug",
"else",
"DEFAULT_TIMEFORMAT",
",",
"gmtime",
... | Gives current time as tuple (t, t_str) where
t is integer portion from time.time()
t_str string of t using DEFAULT_TIMEFORMAT | [
"Gives",
"current",
"time",
"as",
"tuple",
"(",
"t",
"t_str",
")",
"where",
"t",
"is",
"integer",
"portion",
"from",
"time",
".",
"time",
"()",
"t_str",
"string",
"of",
"t",
"using",
"DEFAULT_TIMEFORMAT"
] | train | https://github.com/clearclaw/logtool/blob/e34c9a580538a9a14fec9b4bbab8b8df92ad36e7/logtool/logtime.py#L23-L33 |
luismasuelli/python-cantrips | cantrips/console.py | input | def input(message, until, single_char=False, transform=lambda a: a):
"""
Keeps asking for input (each time in a new line) until a condition
over the input text evaluates to true. Returns the input. This
input can be done using text input or character input.
"""
def _getch(message):
... | python | def input(message, until, single_char=False, transform=lambda a: a):
"""
Keeps asking for input (each time in a new line) until a condition
over the input text evaluates to true. Returns the input. This
input can be done using text input or character input.
"""
def _getch(message):
... | [
"def",
"input",
"(",
"message",
",",
"until",
",",
"single_char",
"=",
"False",
",",
"transform",
"=",
"lambda",
"a",
":",
"a",
")",
":",
"def",
"_getch",
"(",
"message",
")",
":",
"print",
"(",
"message",
",",
"end",
"=",
"''",
")",
"return",
"get... | Keeps asking for input (each time in a new line) until a condition
over the input text evaluates to true. Returns the input. This
input can be done using text input or character input. | [
"Keeps",
"asking",
"for",
"input",
"(",
"each",
"time",
"in",
"a",
"new",
"line",
")",
"until",
"a",
"condition",
"over",
"the",
"input",
"text",
"evaluates",
"to",
"true",
".",
"Returns",
"the",
"input",
".",
"This",
"input",
"can",
"be",
"done",
"usi... | train | https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/console.py#L50-L63 |
luismasuelli/python-cantrips | cantrips/console.py | input_option | def input_option(message, options="yn", error_message=None):
"""
Reads an option from the screen, with a specified prompt.
Keeps asking until a valid option is sent by the user.
"""
def _valid(character):
if character not in options:
print(error_message % character)
retur... | python | def input_option(message, options="yn", error_message=None):
"""
Reads an option from the screen, with a specified prompt.
Keeps asking until a valid option is sent by the user.
"""
def _valid(character):
if character not in options:
print(error_message % character)
retur... | [
"def",
"input_option",
"(",
"message",
",",
"options",
"=",
"\"yn\"",
",",
"error_message",
"=",
"None",
")",
":",
"def",
"_valid",
"(",
"character",
")",
":",
"if",
"character",
"not",
"in",
"options",
":",
"print",
"(",
"error_message",
"%",
"character",... | Reads an option from the screen, with a specified prompt.
Keeps asking until a valid option is sent by the user. | [
"Reads",
"an",
"option",
"from",
"the",
"screen",
"with",
"a",
"specified",
"prompt",
".",
"Keeps",
"asking",
"until",
"a",
"valid",
"option",
"is",
"sent",
"by",
"the",
"user",
"."
] | train | https://github.com/luismasuelli/python-cantrips/blob/dba2742c1d1a60863bb65f4a291464f6e68eb2ee/cantrips/console.py#L66-L74 |
aquatix/python-utilkit | utilkit/stringutil.py | safe_unicode | def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args) # noqa for undefined-variable
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
try:
return unicode(ascii_te... | python | def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args) # noqa for undefined-variable
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
try:
return unicode(ascii_te... | [
"def",
"safe_unicode",
"(",
"obj",
",",
"*",
"args",
")",
":",
"try",
":",
"return",
"unicode",
"(",
"obj",
",",
"*",
"args",
")",
"# noqa for undefined-variable",
"except",
"UnicodeDecodeError",
":",
"# obj is byte string",
"ascii_text",
"=",
"str",
"(",
"obj... | return the unicode representation of obj | [
"return",
"the",
"unicode",
"representation",
"of",
"obj"
] | train | https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/stringutil.py#L6-L20 |
aquatix/python-utilkit | utilkit/stringutil.py | safe_str | def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
try:
return unicode(obj).encode('unicode_escape') # noqa for undefined-variable
except NameError:
# This is Python... | python | def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
try:
return unicode(obj).encode('unicode_escape') # noqa for undefined-variable
except NameError:
# This is Python... | [
"def",
"safe_str",
"(",
"obj",
")",
":",
"try",
":",
"return",
"str",
"(",
"obj",
")",
"except",
"UnicodeEncodeError",
":",
"# obj is unicode",
"try",
":",
"return",
"unicode",
"(",
"obj",
")",
".",
"encode",
"(",
"'unicode_escape'",
")",
"# noqa for undefin... | return the byte string representation of obj | [
"return",
"the",
"byte",
"string",
"representation",
"of",
"obj"
] | train | https://github.com/aquatix/python-utilkit/blob/1b4a4175381d2175592208619315f399610f915c/utilkit/stringutil.py#L23-L33 |
kathyxchen/crosstalk-correction | crosstalk_correction/crosstalk_correction.py | crosstalk_correction | def crosstalk_correction(pathway_definitions,
random_seed=2015,
gene_set=set(),
all_genes=True,
max_iters=1000):
"""A wrapper function around the maximum impact estimation algorithm.
Parameters
-----------
... | python | def crosstalk_correction(pathway_definitions,
random_seed=2015,
gene_set=set(),
all_genes=True,
max_iters=1000):
"""A wrapper function around the maximum impact estimation algorithm.
Parameters
-----------
... | [
"def",
"crosstalk_correction",
"(",
"pathway_definitions",
",",
"random_seed",
"=",
"2015",
",",
"gene_set",
"=",
"set",
"(",
")",
",",
"all_genes",
"=",
"True",
",",
"max_iters",
"=",
"1000",
")",
":",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
"=",... | A wrapper function around the maximum impact estimation algorithm.
Parameters
-----------
pathway_definitions : dict(str -> set(str))
The original pathway definitions.
A pathway (key) is defined by a set of genes (value).
random_seed : int (default=2015)
Sets the numpy random se... | [
"A",
"wrapper",
"function",
"around",
"the",
"maximum",
"impact",
"estimation",
"algorithm",
"."
] | train | https://github.com/kathyxchen/crosstalk-correction/blob/eac11d54b39ea7ec301b54f8e498adce91713223/crosstalk_correction/crosstalk_correction.py#L8-L98 |
kathyxchen/crosstalk-correction | crosstalk_correction/crosstalk_correction.py | maximum_impact_estimation | def maximum_impact_estimation(membership_matrix, max_iters=1000):
"""An expectation maximization technique that produces pathway definitions
devoid of crosstalk. That is, each gene is mapped to the pathway in
which it has the greatest predicted impact; this removes any overlap
between pathway definition... | python | def maximum_impact_estimation(membership_matrix, max_iters=1000):
"""An expectation maximization technique that produces pathway definitions
devoid of crosstalk. That is, each gene is mapped to the pathway in
which it has the greatest predicted impact; this removes any overlap
between pathway definition... | [
"def",
"maximum_impact_estimation",
"(",
"membership_matrix",
",",
"max_iters",
"=",
"1000",
")",
":",
"# Initialize the probability vector as the sum of each column in the",
"# membership matrix normalized by the sum of the entire membership matrix.",
"# The probability at some index j in t... | An expectation maximization technique that produces pathway definitions
devoid of crosstalk. That is, each gene is mapped to the pathway in
which it has the greatest predicted impact; this removes any overlap
between pathway definitions.
Parameters
-----------
membership_matrix : numpy.array(fl... | [
"An",
"expectation",
"maximization",
"technique",
"that",
"produces",
"pathway",
"definitions",
"devoid",
"of",
"crosstalk",
".",
"That",
"is",
"each",
"gene",
"is",
"mapped",
"to",
"the",
"pathway",
"in",
"which",
"it",
"has",
"the",
"greatest",
"predicted",
... | train | https://github.com/kathyxchen/crosstalk-correction/blob/eac11d54b39ea7ec301b54f8e498adce91713223/crosstalk_correction/crosstalk_correction.py#L101-L174 |
kathyxchen/crosstalk-correction | crosstalk_correction/crosstalk_correction.py | initialize_membership_matrix | def initialize_membership_matrix(gene_row_names, pathway_definitions):
"""Create the binary gene-to-pathway membership matrix that
will be considered in the maximum impact estimation procedure.
Parameters
-----------
gene_row_names : set(str)
The genes for which we want to assess pathway me... | python | def initialize_membership_matrix(gene_row_names, pathway_definitions):
"""Create the binary gene-to-pathway membership matrix that
will be considered in the maximum impact estimation procedure.
Parameters
-----------
gene_row_names : set(str)
The genes for which we want to assess pathway me... | [
"def",
"initialize_membership_matrix",
"(",
"gene_row_names",
",",
"pathway_definitions",
")",
":",
"membership",
"=",
"[",
"]",
"for",
"pathway",
",",
"full_definition",
"in",
"pathway_definitions",
".",
"items",
"(",
")",
":",
"pathway_genes",
"=",
"list",
"(",
... | Create the binary gene-to-pathway membership matrix that
will be considered in the maximum impact estimation procedure.
Parameters
-----------
gene_row_names : set(str)
The genes for which we want to assess pathway membership
pathway_definitions : dict(str -> set(str))
Pathway defin... | [
"Create",
"the",
"binary",
"gene",
"-",
"to",
"-",
"pathway",
"membership",
"matrix",
"that",
"will",
"be",
"considered",
"in",
"the",
"maximum",
"impact",
"estimation",
"procedure",
"."
] | train | https://github.com/kathyxchen/crosstalk-correction/blob/eac11d54b39ea7ec301b54f8e498adce91713223/crosstalk_correction/crosstalk_correction.py#L177-L198 |
kathyxchen/crosstalk-correction | crosstalk_correction/crosstalk_correction.py | index_element_map | def index_element_map(arr):
"""Map the indices of the array to the respective elements.
Parameters
-----------
arr : list(a)
The array to process, of generic type a
Returns
-----------
dict(int -> a), a dictionary corresponding the index to the element
"""
index_to_element ... | python | def index_element_map(arr):
"""Map the indices of the array to the respective elements.
Parameters
-----------
arr : list(a)
The array to process, of generic type a
Returns
-----------
dict(int -> a), a dictionary corresponding the index to the element
"""
index_to_element ... | [
"def",
"index_element_map",
"(",
"arr",
")",
":",
"index_to_element",
"=",
"{",
"}",
"for",
"index",
",",
"element",
"in",
"enumerate",
"(",
"arr",
")",
":",
"index_to_element",
"[",
"index",
"]",
"=",
"element",
"return",
"index_to_element"
] | Map the indices of the array to the respective elements.
Parameters
-----------
arr : list(a)
The array to process, of generic type a
Returns
-----------
dict(int -> a), a dictionary corresponding the index to the element | [
"Map",
"the",
"indices",
"of",
"the",
"array",
"to",
"the",
"respective",
"elements",
"."
] | train | https://github.com/kathyxchen/crosstalk-correction/blob/eac11d54b39ea7ec301b54f8e498adce91713223/crosstalk_correction/crosstalk_correction.py#L201-L216 |
kathyxchen/crosstalk-correction | crosstalk_correction/crosstalk_correction.py | _apply_correction_on_genes | def _apply_correction_on_genes(genes,
pathway_column_names,
pathway_definitions):
"""Helper function to create the gene-to-pathway
membership matrix and apply crosstalk correction on that
matrix. Returns the crosstalk-corrected pathway definition... | python | def _apply_correction_on_genes(genes,
pathway_column_names,
pathway_definitions):
"""Helper function to create the gene-to-pathway
membership matrix and apply crosstalk correction on that
matrix. Returns the crosstalk-corrected pathway definition... | [
"def",
"_apply_correction_on_genes",
"(",
"genes",
",",
"pathway_column_names",
",",
"pathway_definitions",
")",
":",
"gene_row_names",
"=",
"index_element_map",
"(",
"genes",
")",
"membership_matrix",
"=",
"initialize_membership_matrix",
"(",
"genes",
",",
"pathway_defin... | Helper function to create the gene-to-pathway
membership matrix and apply crosstalk correction on that
matrix. Returns the crosstalk-corrected pathway definitions
for the input `genes.` | [
"Helper",
"function",
"to",
"create",
"the",
"gene",
"-",
"to",
"-",
"pathway",
"membership",
"matrix",
"and",
"apply",
"crosstalk",
"correction",
"on",
"that",
"matrix",
".",
"Returns",
"the",
"crosstalk",
"-",
"corrected",
"pathway",
"definitions",
"for",
"t... | train | https://github.com/kathyxchen/crosstalk-correction/blob/eac11d54b39ea7ec301b54f8e498adce91713223/crosstalk_correction/crosstalk_correction.py#L219-L236 |
kathyxchen/crosstalk-correction | crosstalk_correction/crosstalk_correction.py | _update_pathway_definitions | def _update_pathway_definitions(crosstalk_corrected_index_map,
gene_row_names,
pathway_column_names):
"""Helper function to convert the mapping of int
(pathway id -> list of gene ids) to the corresponding pathway
names and gene identifiers.
... | python | def _update_pathway_definitions(crosstalk_corrected_index_map,
gene_row_names,
pathway_column_names):
"""Helper function to convert the mapping of int
(pathway id -> list of gene ids) to the corresponding pathway
names and gene identifiers.
... | [
"def",
"_update_pathway_definitions",
"(",
"crosstalk_corrected_index_map",
",",
"gene_row_names",
",",
"pathway_column_names",
")",
":",
"corrected_pathway_definitions",
"=",
"{",
"}",
"for",
"pathway_index",
",",
"gene_indices",
"in",
"crosstalk_corrected_index_map",
".",
... | Helper function to convert the mapping of int
(pathway id -> list of gene ids) to the corresponding pathway
names and gene identifiers. | [
"Helper",
"function",
"to",
"convert",
"the",
"mapping",
"of",
"int",
"(",
"pathway",
"id",
"-",
">",
"list",
"of",
"gene",
"ids",
")",
"to",
"the",
"corresponding",
"pathway",
"names",
"and",
"gene",
"identifiers",
"."
] | train | https://github.com/kathyxchen/crosstalk-correction/blob/eac11d54b39ea7ec301b54f8e498adce91713223/crosstalk_correction/crosstalk_correction.py#L239-L251 |
kathyxchen/crosstalk-correction | crosstalk_correction/crosstalk_correction.py | _update_probabilities | def _update_probabilities(pr, membership_matrix):
"""Updates the probability vector for each iteration of the
expectation maximum algorithm in maximum impact estimation.
Parameters
-----------
pr : numpy.array(float), shape = [k]
The current vector of probabilities. An element at index j,
... | python | def _update_probabilities(pr, membership_matrix):
"""Updates the probability vector for each iteration of the
expectation maximum algorithm in maximum impact estimation.
Parameters
-----------
pr : numpy.array(float), shape = [k]
The current vector of probabilities. An element at index j,
... | [
"def",
"_update_probabilities",
"(",
"pr",
",",
"membership_matrix",
")",
":",
"n",
",",
"k",
"=",
"membership_matrix",
".",
"shape",
"pathway_col_sums",
"=",
"np",
".",
"sum",
"(",
"membership_matrix",
",",
"axis",
"=",
"0",
")",
"weighted_pathway_col_sums",
... | Updates the probability vector for each iteration of the
expectation maximum algorithm in maximum impact estimation.
Parameters
-----------
pr : numpy.array(float), shape = [k]
The current vector of probabilities. An element at index j,
where j is between 0 and k - 1, corresponds to the... | [
"Updates",
"the",
"probability",
"vector",
"for",
"each",
"iteration",
"of",
"the",
"expectation",
"maximum",
"algorithm",
"in",
"maximum",
"impact",
"estimation",
"."
] | train | https://github.com/kathyxchen/crosstalk-correction/blob/eac11d54b39ea7ec301b54f8e498adce91713223/crosstalk_correction/crosstalk_correction.py#L254-L307 |
kathyxchen/crosstalk-correction | crosstalk_correction/crosstalk_correction.py | _replace_zeros | def _replace_zeros(arr, default_min_value):
"""Substitute 0s in the list with a near-zero value.
Parameters
-----------
arr : numpy.array(float)
default_min_value : float
If the smallest non-zero element in `arr` is greater than the default,
use the default instead.
Returns
... | python | def _replace_zeros(arr, default_min_value):
"""Substitute 0s in the list with a near-zero value.
Parameters
-----------
arr : numpy.array(float)
default_min_value : float
If the smallest non-zero element in `arr` is greater than the default,
use the default instead.
Returns
... | [
"def",
"_replace_zeros",
"(",
"arr",
",",
"default_min_value",
")",
":",
"min_nonzero_value",
"=",
"min",
"(",
"default_min_value",
",",
"np",
".",
"min",
"(",
"arr",
"[",
"arr",
">",
"0",
"]",
")",
")",
"closest_to_zero",
"=",
"np",
".",
"nextafter",
"(... | Substitute 0s in the list with a near-zero value.
Parameters
-----------
arr : numpy.array(float)
default_min_value : float
If the smallest non-zero element in `arr` is greater than the default,
use the default instead.
Returns
-----------
numpy.array(float) | [
"Substitute",
"0s",
"in",
"the",
"list",
"with",
"a",
"near",
"-",
"zero",
"value",
"."
] | train | https://github.com/kathyxchen/crosstalk-correction/blob/eac11d54b39ea7ec301b54f8e498adce91713223/crosstalk_correction/crosstalk_correction.py#L310-L327 |
listen-lavender/webcrawl | webcrawl/task.py | patch_thread | def patch_thread(threading=True, _threading_local=True, Queue=True, Event=False):
"""Replace the standard :mod:`thread` module to make it greenlet-based.
If *threading* is true (the default), also patch ``threading``.
If *_threading_local* is true (the default), also patch ``_threading_local.local``.
... | python | def patch_thread(threading=True, _threading_local=True, Queue=True, Event=False):
"""Replace the standard :mod:`thread` module to make it greenlet-based.
If *threading* is true (the default), also patch ``threading``.
If *_threading_local* is true (the default), also patch ``_threading_local.local``.
... | [
"def",
"patch_thread",
"(",
"threading",
"=",
"True",
",",
"_threading_local",
"=",
"True",
",",
"Queue",
"=",
"True",
",",
"Event",
"=",
"False",
")",
":",
"monkey",
".",
"patch_module",
"(",
"'thread'",
")",
"if",
"threading",
":",
"monkey",
".",
"patc... | Replace the standard :mod:`thread` module to make it greenlet-based.
If *threading* is true (the default), also patch ``threading``.
If *_threading_local* is true (the default), also patch ``_threading_local.local``. | [
"Replace",
"the",
"standard",
":",
"mod",
":",
"thread",
"module",
"to",
"make",
"it",
"greenlet",
"-",
"based",
".",
"If",
"*",
"threading",
"*",
"is",
"true",
"(",
"the",
"default",
")",
"also",
"patch",
"threading",
".",
"If",
"*",
"_threading_local",... | train | https://github.com/listen-lavender/webcrawl/blob/905dcfa6e6934aac764045660c0efcef28eae1e6/webcrawl/task.py#L29-L47 |
shi-cong/PYSTUDY | PYSTUDY/ml/knnlib.py | classify | def classify(in_x, groups, labels, k):
"""分类"""
# 计算欧式距离
gl = array_len(groups)
tmp = tile(in_x, (gl, 1)) - groups
tmp = exponential_operation(tmp, 2)
tmp = array_sum(tmp)
tmp = exponential_operation(tmp, 0.5)
# 得到排序后的数组的索引
arg = argsort(tmp)
# 计算最相似数据的前k个数据的分类次数
cc = odict... | python | def classify(in_x, groups, labels, k):
"""分类"""
# 计算欧式距离
gl = array_len(groups)
tmp = tile(in_x, (gl, 1)) - groups
tmp = exponential_operation(tmp, 2)
tmp = array_sum(tmp)
tmp = exponential_operation(tmp, 0.5)
# 得到排序后的数组的索引
arg = argsort(tmp)
# 计算最相似数据的前k个数据的分类次数
cc = odict... | [
"def",
"classify",
"(",
"in_x",
",",
"groups",
",",
"labels",
",",
"k",
")",
":",
"# 计算欧式距离",
"gl",
"=",
"array_len",
"(",
"groups",
")",
"tmp",
"=",
"tile",
"(",
"in_x",
",",
"(",
"gl",
",",
"1",
")",
")",
"-",
"groups",
"tmp",
"=",
"exponential... | 分类 | [
"分类"
] | train | https://github.com/shi-cong/PYSTUDY/blob/c8da7128ea18ecaa5849f2066d321e70d6f97f70/PYSTUDY/ml/knnlib.py#L27-L45 |
DasIch/argvard | argvard/annotations.py | annotations | def annotations(from_defaults=True, **kwargs):
"""
A function decorator which coerces argument values to the annotated types.
This decorator is implicitly applied to command and option functions.
Explicitly wrapping your functions with it allows more fine-grained
configuration and the usage of annot... | python | def annotations(from_defaults=True, **kwargs):
"""
A function decorator which coerces argument values to the annotated types.
This decorator is implicitly applied to command and option functions.
Explicitly wrapping your functions with it allows more fine-grained
configuration and the usage of annot... | [
"def",
"annotations",
"(",
"from_defaults",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"func",
"=",
"set_annotations",
"(",
"*",
"*",
"kwargs",
")",
"(",
"func",
")",
"if",
"from_defaults",
":",
"func",
... | A function decorator which coerces argument values to the annotated types.
This decorator is implicitly applied to command and option functions.
Explicitly wrapping your functions with it allows more fine-grained
configuration and the usage of annotations in Python 2. Applying this
decorator multiple ti... | [
"A",
"function",
"decorator",
"which",
"coerces",
"argument",
"values",
"to",
"the",
"annotated",
"types",
".",
"This",
"decorator",
"is",
"implicitly",
"applied",
"to",
"command",
"and",
"option",
"functions",
".",
"Explicitly",
"wrapping",
"your",
"functions",
... | train | https://github.com/DasIch/argvard/blob/2603e323a995e0915ce41fcf49e2a82519556195/argvard/annotations.py#L41-L62 |
noobermin/lspreader | bin/pmov.py | hdfoutput | def hdfoutput(outname, frames, dozip=False):
'''Outputs the frames to an hdf file.'''
with h5.File(outname,'a') as f:
for frame in frames:
group=str(frame['step']);
h5w(f, frame, group=group,
compression='lzf' if dozip else None); | python | def hdfoutput(outname, frames, dozip=False):
'''Outputs the frames to an hdf file.'''
with h5.File(outname,'a') as f:
for frame in frames:
group=str(frame['step']);
h5w(f, frame, group=group,
compression='lzf' if dozip else None); | [
"def",
"hdfoutput",
"(",
"outname",
",",
"frames",
",",
"dozip",
"=",
"False",
")",
":",
"with",
"h5",
".",
"File",
"(",
"outname",
",",
"'a'",
")",
"as",
"f",
":",
"for",
"frame",
"in",
"frames",
":",
"group",
"=",
"str",
"(",
"frame",
"[",
"'st... | Outputs the frames to an hdf file. | [
"Outputs",
"the",
"frames",
"to",
"an",
"hdf",
"file",
"."
] | train | https://github.com/noobermin/lspreader/blob/903b9d6427513b07986ffacf76cbca54e18d8be6/bin/pmov.py#L42-L48 |
cdeboever3/cdpybio | cdpybio/bedtools.py | beds_to_boolean | def beds_to_boolean(beds, ref=None, beds_sorted=False, ref_sorted=False,
**kwargs):
"""
Compare a list of bed files or BedTool objects to a reference bed file and
create a boolean matrix where each row is an interval and each column is a 1
if that file has an interval that overlaps t... | python | def beds_to_boolean(beds, ref=None, beds_sorted=False, ref_sorted=False,
**kwargs):
"""
Compare a list of bed files or BedTool objects to a reference bed file and
create a boolean matrix where each row is an interval and each column is a 1
if that file has an interval that overlaps t... | [
"def",
"beds_to_boolean",
"(",
"beds",
",",
"ref",
"=",
"None",
",",
"beds_sorted",
"=",
"False",
",",
"ref_sorted",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"beds",
"=",
"copy",
".",
"deepcopy",
"(",
"beds",
")",
"fns",
"=",
"[",
"]",
"for... | Compare a list of bed files or BedTool objects to a reference bed file and
create a boolean matrix where each row is an interval and each column is a 1
if that file has an interval that overlaps the row interval and a 0
otherwise. If no reference bed is provided, the provided bed files will be
merged in... | [
"Compare",
"a",
"list",
"of",
"bed",
"files",
"or",
"BedTool",
"objects",
"to",
"a",
"reference",
"bed",
"file",
"and",
"create",
"a",
"boolean",
"matrix",
"where",
"each",
"row",
"is",
"an",
"interval",
"and",
"each",
"column",
"is",
"a",
"1",
"if",
"... | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/bedtools.py#L271-L346 |
cdeboever3/cdpybio | cdpybio/bedtools.py | combine | def combine(beds, beds_sorted=False, postmerge=True):
"""
Combine a list of bed files or BedTool objects into a single BedTool object.
Parameters
----------
beds : list
List of paths to bed files or BedTool objects.
beds_sorted : boolean
Whether the bed files in beds are alread... | python | def combine(beds, beds_sorted=False, postmerge=True):
"""
Combine a list of bed files or BedTool objects into a single BedTool object.
Parameters
----------
beds : list
List of paths to bed files or BedTool objects.
beds_sorted : boolean
Whether the bed files in beds are alread... | [
"def",
"combine",
"(",
"beds",
",",
"beds_sorted",
"=",
"False",
",",
"postmerge",
"=",
"True",
")",
":",
"beds",
"=",
"copy",
".",
"deepcopy",
"(",
"beds",
")",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"beds",
")",
":",
"if",
"type",
"(",
"... | Combine a list of bed files or BedTool objects into a single BedTool object.
Parameters
----------
beds : list
List of paths to bed files or BedTool objects.
beds_sorted : boolean
Whether the bed files in beds are already sorted. If False, all bed
files in beds will be sorted.
... | [
"Combine",
"a",
"list",
"of",
"bed",
"files",
"or",
"BedTool",
"objects",
"into",
"a",
"single",
"BedTool",
"object",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/bedtools.py#L348-L385 |
cdeboever3/cdpybio | cdpybio/bedtools.py | write_bed_with_trackline | def write_bed_with_trackline(bed, out, trackline, add_chr=False):
"""
Read a bed file and write a copy with a trackline. Here's a simple trackline
example: 'track type=bed name="cool" description="A cool track."'
Parameters
----------
bed : str
Input bed file name.
out : str
... | python | def write_bed_with_trackline(bed, out, trackline, add_chr=False):
"""
Read a bed file and write a copy with a trackline. Here's a simple trackline
example: 'track type=bed name="cool" description="A cool track."'
Parameters
----------
bed : str
Input bed file name.
out : str
... | [
"def",
"write_bed_with_trackline",
"(",
"bed",
",",
"out",
",",
"trackline",
",",
"add_chr",
"=",
"False",
")",
":",
"df",
"=",
"pd",
".",
"read_table",
"(",
"bed",
",",
"index_col",
"=",
"None",
",",
"header",
"=",
"None",
")",
"bt",
"=",
"pbt",
"."... | Read a bed file and write a copy with a trackline. Here's a simple trackline
example: 'track type=bed name="cool" description="A cool track."'
Parameters
----------
bed : str
Input bed file name.
out : str
Output bed file name.
trackline : str
UCSC trackline.
add_ch... | [
"Read",
"a",
"bed",
"file",
"and",
"write",
"a",
"copy",
"with",
"a",
"trackline",
".",
"Here",
"s",
"a",
"simple",
"trackline",
"example",
":",
"track",
"type",
"=",
"bed",
"name",
"=",
"cool",
"description",
"=",
"A",
"cool",
"track",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/bedtools.py#L388-L412 |
cdeboever3/cdpybio | cdpybio/bedtools.py | strip_chr | def strip_chr(bt):
"""Strip 'chr' from chromosomes for BedTool object
Parameters
----------
bt : pybedtools.BedTool
BedTool to strip 'chr' from.
Returns
-------
out : pybedtools.BedTool
New BedTool with 'chr' stripped from chromosome names.
"""
try:
df = pd... | python | def strip_chr(bt):
"""Strip 'chr' from chromosomes for BedTool object
Parameters
----------
bt : pybedtools.BedTool
BedTool to strip 'chr' from.
Returns
-------
out : pybedtools.BedTool
New BedTool with 'chr' stripped from chromosome names.
"""
try:
df = pd... | [
"def",
"strip_chr",
"(",
"bt",
")",
":",
"try",
":",
"df",
"=",
"pd",
".",
"read_table",
"(",
"bt",
".",
"fn",
",",
"header",
"=",
"None",
",",
"dtype",
"=",
"str",
")",
"# If the try fails, I assume that's because the file has a trackline. Note",
"# that I don'... | Strip 'chr' from chromosomes for BedTool object
Parameters
----------
bt : pybedtools.BedTool
BedTool to strip 'chr' from.
Returns
-------
out : pybedtools.BedTool
New BedTool with 'chr' stripped from chromosome names. | [
"Strip",
"chr",
"from",
"chromosomes",
"for",
"BedTool",
"object"
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/bedtools.py#L414-L438 |
cdeboever3/cdpybio | cdpybio/bedtools.py | intervals_to_bed | def intervals_to_bed(intervals):
"""
Convert list of intervals of format chr1:100-200 or chr1:100-200:+ to
BedTool object.
Parameters
----------
intervals : array-like
List of intervals.
Returns
-------
bt : pybedtools.BedTool
BedTool with one line for each interva... | python | def intervals_to_bed(intervals):
"""
Convert list of intervals of format chr1:100-200 or chr1:100-200:+ to
BedTool object.
Parameters
----------
intervals : array-like
List of intervals.
Returns
-------
bt : pybedtools.BedTool
BedTool with one line for each interva... | [
"def",
"intervals_to_bed",
"(",
"intervals",
")",
":",
"import",
"re",
"strand",
"=",
"re",
".",
"compile",
"(",
"'(.*):(.*)-(.*):(\\+|-)'",
")",
"no_strand",
"=",
"re",
".",
"compile",
"(",
"'(.*):(.*)-(.*)'",
")",
"bed_lines",
"=",
"[",
"]",
"s",
"=",
"F... | Convert list of intervals of format chr1:100-200 or chr1:100-200:+ to
BedTool object.
Parameters
----------
intervals : array-like
List of intervals.
Returns
-------
bt : pybedtools.BedTool
BedTool with one line for each interval. | [
"Convert",
"list",
"of",
"intervals",
"of",
"format",
"chr1",
":",
"100",
"-",
"200",
"or",
"chr1",
":",
"100",
"-",
"200",
":",
"+",
"to",
"BedTool",
"object",
"."
] | train | https://github.com/cdeboever3/cdpybio/blob/38efdf0e11d01bc00a135921cb91a19c03db5d5c/cdpybio/bedtools.py#L466-L496 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.