id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
242,500
|
mgk/thingamon
|
thingamon/client.py
|
Client.publish
|
def publish(self, topic, message):
"""Publish an MQTT message to a topic."""
self.connect()
log.info('publish {}'.format(message))
self.client.publish(topic, message)
|
python
|
def publish(self, topic, message):
"""Publish an MQTT message to a topic."""
self.connect()
log.info('publish {}'.format(message))
self.client.publish(topic, message)
|
[
"def",
"publish",
"(",
"self",
",",
"topic",
",",
"message",
")",
":",
"self",
".",
"connect",
"(",
")",
"log",
".",
"info",
"(",
"'publish {}'",
".",
"format",
"(",
"message",
")",
")",
"self",
".",
"client",
".",
"publish",
"(",
"topic",
",",
"message",
")"
] |
Publish an MQTT message to a topic.
|
[
"Publish",
"an",
"MQTT",
"message",
"to",
"a",
"topic",
"."
] |
3f7d68dc2131c347473af15cd5f7d4b669407c6b
|
https://github.com/mgk/thingamon/blob/3f7d68dc2131c347473af15cd5f7d4b669407c6b/thingamon/client.py#L95-L99
|
242,501
|
JonLiuFYI/pkdx
|
pkdx/pkdx/scrape_abilities.py
|
get_abilities
|
def get_abilities():
"""Visit Bulbapedia and pull names and descriptions from the table, 'list of Abilities.' Save as JSON."""
page = requests.get('http://bulbapedia.bulbagarden.net/wiki/Ability')
soup = bs4.BeautifulSoup(page.text)
table = soup.find("table", {"class": "sortable"})
tablerows = [tr for tr in table.children if tr != '\n'][1:]
abilities = {}
for tr in tablerows:
cells = tr.find_all('td')
ability_name = cells[1].get_text().strip().replace(' ', '-').lower()
ability_desc = unicode(cells[2].get_text().strip())
abilities[ability_name] = ability_desc
srcpath = path.dirname(__file__)
with io.open(path.join(srcpath, 'abilities.json'), 'w', encoding='utf-8') as f:
f.write(json.dumps(abilities, ensure_ascii=False))
|
python
|
def get_abilities():
"""Visit Bulbapedia and pull names and descriptions from the table, 'list of Abilities.' Save as JSON."""
page = requests.get('http://bulbapedia.bulbagarden.net/wiki/Ability')
soup = bs4.BeautifulSoup(page.text)
table = soup.find("table", {"class": "sortable"})
tablerows = [tr for tr in table.children if tr != '\n'][1:]
abilities = {}
for tr in tablerows:
cells = tr.find_all('td')
ability_name = cells[1].get_text().strip().replace(' ', '-').lower()
ability_desc = unicode(cells[2].get_text().strip())
abilities[ability_name] = ability_desc
srcpath = path.dirname(__file__)
with io.open(path.join(srcpath, 'abilities.json'), 'w', encoding='utf-8') as f:
f.write(json.dumps(abilities, ensure_ascii=False))
|
[
"def",
"get_abilities",
"(",
")",
":",
"page",
"=",
"requests",
".",
"get",
"(",
"'http://bulbapedia.bulbagarden.net/wiki/Ability'",
")",
"soup",
"=",
"bs4",
".",
"BeautifulSoup",
"(",
"page",
".",
"text",
")",
"table",
"=",
"soup",
".",
"find",
"(",
"\"table\"",
",",
"{",
"\"class\"",
":",
"\"sortable\"",
"}",
")",
"tablerows",
"=",
"[",
"tr",
"for",
"tr",
"in",
"table",
".",
"children",
"if",
"tr",
"!=",
"'\\n'",
"]",
"[",
"1",
":",
"]",
"abilities",
"=",
"{",
"}",
"for",
"tr",
"in",
"tablerows",
":",
"cells",
"=",
"tr",
".",
"find_all",
"(",
"'td'",
")",
"ability_name",
"=",
"cells",
"[",
"1",
"]",
".",
"get_text",
"(",
")",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"' '",
",",
"'-'",
")",
".",
"lower",
"(",
")",
"ability_desc",
"=",
"unicode",
"(",
"cells",
"[",
"2",
"]",
".",
"get_text",
"(",
")",
".",
"strip",
"(",
")",
")",
"abilities",
"[",
"ability_name",
"]",
"=",
"ability_desc",
"srcpath",
"=",
"path",
".",
"dirname",
"(",
"__file__",
")",
"with",
"io",
".",
"open",
"(",
"path",
".",
"join",
"(",
"srcpath",
",",
"'abilities.json'",
")",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"abilities",
",",
"ensure_ascii",
"=",
"False",
")",
")"
] |
Visit Bulbapedia and pull names and descriptions from the table, 'list of Abilities.' Save as JSON.
|
[
"Visit",
"Bulbapedia",
"and",
"pull",
"names",
"and",
"descriptions",
"from",
"the",
"table",
"list",
"of",
"Abilities",
".",
"Save",
"as",
"JSON",
"."
] |
269e9814df074e0df25972fad04539a644d73a3c
|
https://github.com/JonLiuFYI/pkdx/blob/269e9814df074e0df25972fad04539a644d73a3c/pkdx/pkdx/scrape_abilities.py#L12-L28
|
242,502
|
openp2pdesign/makerlabs
|
makerlabs/techshop_ws.py
|
data_from_techshop_ws
|
def data_from_techshop_ws(tws_url):
"""Scrapes data from techshop.ws."""
r = requests.get(tws_url)
if r.status_code == 200:
data = BeautifulSoup(r.text, "lxml")
else:
data = "There was an error while accessing data on techshop.ws."
return data
|
python
|
def data_from_techshop_ws(tws_url):
"""Scrapes data from techshop.ws."""
r = requests.get(tws_url)
if r.status_code == 200:
data = BeautifulSoup(r.text, "lxml")
else:
data = "There was an error while accessing data on techshop.ws."
return data
|
[
"def",
"data_from_techshop_ws",
"(",
"tws_url",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"tws_url",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"data",
"=",
"BeautifulSoup",
"(",
"r",
".",
"text",
",",
"\"lxml\"",
")",
"else",
":",
"data",
"=",
"\"There was an error while accessing data on techshop.ws.\"",
"return",
"data"
] |
Scrapes data from techshop.ws.
|
[
"Scrapes",
"data",
"from",
"techshop",
".",
"ws",
"."
] |
b5838440174f10d370abb671358db9a99d7739fd
|
https://github.com/openp2pdesign/makerlabs/blob/b5838440174f10d370abb671358db9a99d7739fd/makerlabs/techshop_ws.py#L38-L47
|
242,503
|
mgbarrero/xbob.db.atvskeystroke
|
xbob/db/atvskeystroke/query.py
|
Database.has_client_id
|
def has_client_id(self, id):
"""Returns True if we have a client with a certain integer identifier"""
return self.query(Client).filter(Client.id==id).count() != 0
|
python
|
def has_client_id(self, id):
"""Returns True if we have a client with a certain integer identifier"""
return self.query(Client).filter(Client.id==id).count() != 0
|
[
"def",
"has_client_id",
"(",
"self",
",",
"id",
")",
":",
"return",
"self",
".",
"query",
"(",
"Client",
")",
".",
"filter",
"(",
"Client",
".",
"id",
"==",
"id",
")",
".",
"count",
"(",
")",
"!=",
"0"
] |
Returns True if we have a client with a certain integer identifier
|
[
"Returns",
"True",
"if",
"we",
"have",
"a",
"client",
"with",
"a",
"certain",
"integer",
"identifier"
] |
b7358a73e21757b43334df7c89ba057b377ca704
|
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L142-L145
|
242,504
|
mgbarrero/xbob.db.atvskeystroke
|
xbob/db/atvskeystroke/query.py
|
Database.client
|
def client(self, id):
"""Returns the client object in the database given a certain id. Raises
an error if that does not exist."""
return self.query(Client).filter(Client.id==id).one()
|
python
|
def client(self, id):
"""Returns the client object in the database given a certain id. Raises
an error if that does not exist."""
return self.query(Client).filter(Client.id==id).one()
|
[
"def",
"client",
"(",
"self",
",",
"id",
")",
":",
"return",
"self",
".",
"query",
"(",
"Client",
")",
".",
"filter",
"(",
"Client",
".",
"id",
"==",
"id",
")",
".",
"one",
"(",
")"
] |
Returns the client object in the database given a certain id. Raises
an error if that does not exist.
|
[
"Returns",
"the",
"client",
"object",
"in",
"the",
"database",
"given",
"a",
"certain",
"id",
".",
"Raises",
"an",
"error",
"if",
"that",
"does",
"not",
"exist",
"."
] |
b7358a73e21757b43334df7c89ba057b377ca704
|
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L147-L151
|
242,505
|
mgbarrero/xbob.db.atvskeystroke
|
xbob/db/atvskeystroke/query.py
|
Database.protocol_names
|
def protocol_names(self):
"""Returns all registered protocol names"""
l = self.protocols()
retval = [str(k.name) for k in l]
return retval
|
python
|
def protocol_names(self):
"""Returns all registered protocol names"""
l = self.protocols()
retval = [str(k.name) for k in l]
return retval
|
[
"def",
"protocol_names",
"(",
"self",
")",
":",
"l",
"=",
"self",
".",
"protocols",
"(",
")",
"retval",
"=",
"[",
"str",
"(",
"k",
".",
"name",
")",
"for",
"k",
"in",
"l",
"]",
"return",
"retval"
] |
Returns all registered protocol names
|
[
"Returns",
"all",
"registered",
"protocol",
"names"
] |
b7358a73e21757b43334df7c89ba057b377ca704
|
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L232-L237
|
242,506
|
mgbarrero/xbob.db.atvskeystroke
|
xbob/db/atvskeystroke/query.py
|
Database.has_protocol
|
def has_protocol(self, name):
"""Tells if a certain protocol is available"""
return self.query(Protocol).filter(Protocol.name==name).count() != 0
|
python
|
def has_protocol(self, name):
"""Tells if a certain protocol is available"""
return self.query(Protocol).filter(Protocol.name==name).count() != 0
|
[
"def",
"has_protocol",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"query",
"(",
"Protocol",
")",
".",
"filter",
"(",
"Protocol",
".",
"name",
"==",
"name",
")",
".",
"count",
"(",
")",
"!=",
"0"
] |
Tells if a certain protocol is available
|
[
"Tells",
"if",
"a",
"certain",
"protocol",
"is",
"available"
] |
b7358a73e21757b43334df7c89ba057b377ca704
|
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L244-L247
|
242,507
|
mgbarrero/xbob.db.atvskeystroke
|
xbob/db/atvskeystroke/query.py
|
Database.protocol
|
def protocol(self, name):
"""Returns the protocol object in the database given a certain name. Raises
an error if that does not exist."""
return self.query(Protocol).filter(Protocol.name==name).one()
|
python
|
def protocol(self, name):
"""Returns the protocol object in the database given a certain name. Raises
an error if that does not exist."""
return self.query(Protocol).filter(Protocol.name==name).one()
|
[
"def",
"protocol",
"(",
"self",
",",
"name",
")",
":",
"return",
"self",
".",
"query",
"(",
"Protocol",
")",
".",
"filter",
"(",
"Protocol",
".",
"name",
"==",
"name",
")",
".",
"one",
"(",
")"
] |
Returns the protocol object in the database given a certain name. Raises
an error if that does not exist.
|
[
"Returns",
"the",
"protocol",
"object",
"in",
"the",
"database",
"given",
"a",
"certain",
"name",
".",
"Raises",
"an",
"error",
"if",
"that",
"does",
"not",
"exist",
"."
] |
b7358a73e21757b43334df7c89ba057b377ca704
|
https://github.com/mgbarrero/xbob.db.atvskeystroke/blob/b7358a73e21757b43334df7c89ba057b377ca704/xbob/db/atvskeystroke/query.py#L249-L253
|
242,508
|
JNRowe/jnrbase
|
jnrbase/i18n.py
|
setup
|
def setup(__pkg: ModuleType) -> Tuple[Callable[[str], str],
Callable[[str, str, int], str]]:
"""Configure ``gettext`` for given package.
Args:
__pkg: Package to use as location for :program:`gettext` files
Returns:
:program:`gettext` functions for singular and plural translations
"""
package_locale = path.join(path.dirname(__pkg.__file__), 'locale')
gettext.install(__pkg.__name__, package_locale)
return gettext.gettext, gettext.ngettext
|
python
|
def setup(__pkg: ModuleType) -> Tuple[Callable[[str], str],
Callable[[str, str, int], str]]:
"""Configure ``gettext`` for given package.
Args:
__pkg: Package to use as location for :program:`gettext` files
Returns:
:program:`gettext` functions for singular and plural translations
"""
package_locale = path.join(path.dirname(__pkg.__file__), 'locale')
gettext.install(__pkg.__name__, package_locale)
return gettext.gettext, gettext.ngettext
|
[
"def",
"setup",
"(",
"__pkg",
":",
"ModuleType",
")",
"->",
"Tuple",
"[",
"Callable",
"[",
"[",
"str",
"]",
",",
"str",
"]",
",",
"Callable",
"[",
"[",
"str",
",",
"str",
",",
"int",
"]",
",",
"str",
"]",
"]",
":",
"package_locale",
"=",
"path",
".",
"join",
"(",
"path",
".",
"dirname",
"(",
"__pkg",
".",
"__file__",
")",
",",
"'locale'",
")",
"gettext",
".",
"install",
"(",
"__pkg",
".",
"__name__",
",",
"package_locale",
")",
"return",
"gettext",
".",
"gettext",
",",
"gettext",
".",
"ngettext"
] |
Configure ``gettext`` for given package.
Args:
__pkg: Package to use as location for :program:`gettext` files
Returns:
:program:`gettext` functions for singular and plural translations
|
[
"Configure",
"gettext",
"for",
"given",
"package",
"."
] |
ae505ef69a9feb739b5f4e62c5a8e6533104d3ea
|
https://github.com/JNRowe/jnrbase/blob/ae505ef69a9feb739b5f4e62c5a8e6533104d3ea/jnrbase/i18n.py#L27-L40
|
242,509
|
jalanb/pysyte
|
pysyte/bash/git.py
|
run
|
def run(sub_command, quiet=False, no_edit=False, no_verify=False):
"""Run a git command
Prefix that sub_command with "git "
then run the command in shell
If quiet if True then do not log results
If no_edit is True then prefix the git command with "GIT_EDITOR=true"
(which does not wait on user's editor)
If the command gives a non-zero status, raise a GitError exception
"""
if _working_dirs[0] != '.':
git_command = 'git -C "%s"' % _working_dirs[0]
else:
git_command = 'git'
edit = 'GIT_EDITOR=true' if no_edit else ''
verify = 'GIT_SSL_NO_VERIFY=true' if no_verify else ''
command = '%s %s %s %s' % (verify, edit, git_command, sub_command)
if not quiet:
logger.info('$ %s', command)
status_, output = getstatusoutput(command)
if status_:
if quiet:
logger.info('$ %s', command)
logger.error('\n%s', output)
if 'unknown revision' in output:
raise UnknownRevision(command, status_, output)
elif 'remote ref does not exist' in output:
raise NoRemoteRef(command, status_, output)
elif 'no such commit' in output:
raise NoSuchCommit(command, status_, output)
elif 'reference already exists' in output:
raise ExistingReference(command, status_, output)
elif re.search('Resolved|CONFLICT|Recorded preimage', output):
raise ResolveError(command, status_, output)
elif re.search('branch named.*already exists', output):
raise ExistingBranch(command, status, output)
raise GitError(command, status_, output)
elif output and not quiet:
logger.info('\n%s', output)
return output
|
python
|
def run(sub_command, quiet=False, no_edit=False, no_verify=False):
"""Run a git command
Prefix that sub_command with "git "
then run the command in shell
If quiet if True then do not log results
If no_edit is True then prefix the git command with "GIT_EDITOR=true"
(which does not wait on user's editor)
If the command gives a non-zero status, raise a GitError exception
"""
if _working_dirs[0] != '.':
git_command = 'git -C "%s"' % _working_dirs[0]
else:
git_command = 'git'
edit = 'GIT_EDITOR=true' if no_edit else ''
verify = 'GIT_SSL_NO_VERIFY=true' if no_verify else ''
command = '%s %s %s %s' % (verify, edit, git_command, sub_command)
if not quiet:
logger.info('$ %s', command)
status_, output = getstatusoutput(command)
if status_:
if quiet:
logger.info('$ %s', command)
logger.error('\n%s', output)
if 'unknown revision' in output:
raise UnknownRevision(command, status_, output)
elif 'remote ref does not exist' in output:
raise NoRemoteRef(command, status_, output)
elif 'no such commit' in output:
raise NoSuchCommit(command, status_, output)
elif 'reference already exists' in output:
raise ExistingReference(command, status_, output)
elif re.search('Resolved|CONFLICT|Recorded preimage', output):
raise ResolveError(command, status_, output)
elif re.search('branch named.*already exists', output):
raise ExistingBranch(command, status, output)
raise GitError(command, status_, output)
elif output and not quiet:
logger.info('\n%s', output)
return output
|
[
"def",
"run",
"(",
"sub_command",
",",
"quiet",
"=",
"False",
",",
"no_edit",
"=",
"False",
",",
"no_verify",
"=",
"False",
")",
":",
"if",
"_working_dirs",
"[",
"0",
"]",
"!=",
"'.'",
":",
"git_command",
"=",
"'git -C \"%s\"'",
"%",
"_working_dirs",
"[",
"0",
"]",
"else",
":",
"git_command",
"=",
"'git'",
"edit",
"=",
"'GIT_EDITOR=true'",
"if",
"no_edit",
"else",
"''",
"verify",
"=",
"'GIT_SSL_NO_VERIFY=true'",
"if",
"no_verify",
"else",
"''",
"command",
"=",
"'%s %s %s %s'",
"%",
"(",
"verify",
",",
"edit",
",",
"git_command",
",",
"sub_command",
")",
"if",
"not",
"quiet",
":",
"logger",
".",
"info",
"(",
"'$ %s'",
",",
"command",
")",
"status_",
",",
"output",
"=",
"getstatusoutput",
"(",
"command",
")",
"if",
"status_",
":",
"if",
"quiet",
":",
"logger",
".",
"info",
"(",
"'$ %s'",
",",
"command",
")",
"logger",
".",
"error",
"(",
"'\\n%s'",
",",
"output",
")",
"if",
"'unknown revision'",
"in",
"output",
":",
"raise",
"UnknownRevision",
"(",
"command",
",",
"status_",
",",
"output",
")",
"elif",
"'remote ref does not exist'",
"in",
"output",
":",
"raise",
"NoRemoteRef",
"(",
"command",
",",
"status_",
",",
"output",
")",
"elif",
"'no such commit'",
"in",
"output",
":",
"raise",
"NoSuchCommit",
"(",
"command",
",",
"status_",
",",
"output",
")",
"elif",
"'reference already exists'",
"in",
"output",
":",
"raise",
"ExistingReference",
"(",
"command",
",",
"status_",
",",
"output",
")",
"elif",
"re",
".",
"search",
"(",
"'Resolved|CONFLICT|Recorded preimage'",
",",
"output",
")",
":",
"raise",
"ResolveError",
"(",
"command",
",",
"status_",
",",
"output",
")",
"elif",
"re",
".",
"search",
"(",
"'branch named.*already exists'",
",",
"output",
")",
":",
"raise",
"ExistingBranch",
"(",
"command",
",",
"status",
",",
"output",
")",
"raise",
"GitError",
"(",
"command",
",",
"status_",
",",
"output",
")",
"elif",
"output",
"and",
"not",
"quiet",
":",
"logger",
".",
"info",
"(",
"'\\n%s'",
",",
"output",
")",
"return",
"output"
] |
Run a git command
Prefix that sub_command with "git "
then run the command in shell
If quiet if True then do not log results
If no_edit is True then prefix the git command with "GIT_EDITOR=true"
(which does not wait on user's editor)
If the command gives a non-zero status, raise a GitError exception
|
[
"Run",
"a",
"git",
"command"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L173-L214
|
242,510
|
jalanb/pysyte
|
pysyte/bash/git.py
|
branches
|
def branches(remotes=False):
"""Return a list of all local branches in the repo
If remotes is true then also include remote branches
Note: the normal '*' indicator for current branch is removed
this method just gives a list of branch names
Use branch() method to determine the current branch
"""
stdout = branch('--list %s' % (remotes and '-a' or ''), quiet=True)
return [_.lstrip('*').strip() for _ in stdout.splitlines()]
|
python
|
def branches(remotes=False):
"""Return a list of all local branches in the repo
If remotes is true then also include remote branches
Note: the normal '*' indicator for current branch is removed
this method just gives a list of branch names
Use branch() method to determine the current branch
"""
stdout = branch('--list %s' % (remotes and '-a' or ''), quiet=True)
return [_.lstrip('*').strip() for _ in stdout.splitlines()]
|
[
"def",
"branches",
"(",
"remotes",
"=",
"False",
")",
":",
"stdout",
"=",
"branch",
"(",
"'--list %s'",
"%",
"(",
"remotes",
"and",
"'-a'",
"or",
"''",
")",
",",
"quiet",
"=",
"True",
")",
"return",
"[",
"_",
".",
"lstrip",
"(",
"'*'",
")",
".",
"strip",
"(",
")",
"for",
"_",
"in",
"stdout",
".",
"splitlines",
"(",
")",
"]"
] |
Return a list of all local branches in the repo
If remotes is true then also include remote branches
Note: the normal '*' indicator for current branch is removed
this method just gives a list of branch names
Use branch() method to determine the current branch
|
[
"Return",
"a",
"list",
"of",
"all",
"local",
"branches",
"in",
"the",
"repo"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L258-L268
|
242,511
|
jalanb/pysyte
|
pysyte/bash/git.py
|
branches_containing
|
def branches_containing(commit):
"""Return a list of branches conatining that commit"""
lines = run('branch --contains %s' % commit).splitlines()
return [l.lstrip('* ') for l in lines]
|
python
|
def branches_containing(commit):
"""Return a list of branches conatining that commit"""
lines = run('branch --contains %s' % commit).splitlines()
return [l.lstrip('* ') for l in lines]
|
[
"def",
"branches_containing",
"(",
"commit",
")",
":",
"lines",
"=",
"run",
"(",
"'branch --contains %s'",
"%",
"commit",
")",
".",
"splitlines",
"(",
")",
"return",
"[",
"l",
".",
"lstrip",
"(",
"'* '",
")",
"for",
"l",
"in",
"lines",
"]"
] |
Return a list of branches conatining that commit
|
[
"Return",
"a",
"list",
"of",
"branches",
"conatining",
"that",
"commit"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L271-L274
|
242,512
|
jalanb/pysyte
|
pysyte/bash/git.py
|
conflicted
|
def conflicted(path_to_file):
"""Whether there are any conflict markers in that file"""
for line in open(path_to_file, 'r'):
for marker in '>="<':
if line.startswith(marker * 8):
return True
return False
|
python
|
def conflicted(path_to_file):
"""Whether there are any conflict markers in that file"""
for line in open(path_to_file, 'r'):
for marker in '>="<':
if line.startswith(marker * 8):
return True
return False
|
[
"def",
"conflicted",
"(",
"path_to_file",
")",
":",
"for",
"line",
"in",
"open",
"(",
"path_to_file",
",",
"'r'",
")",
":",
"for",
"marker",
"in",
"'>=\"<'",
":",
"if",
"line",
".",
"startswith",
"(",
"marker",
"*",
"8",
")",
":",
"return",
"True",
"return",
"False"
] |
Whether there are any conflict markers in that file
|
[
"Whether",
"there",
"are",
"any",
"conflict",
"markers",
"in",
"that",
"file"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L290-L296
|
242,513
|
jalanb/pysyte
|
pysyte/bash/git.py
|
config
|
def config(key, value, local=True):
"""Set that config key to that value
Unless local is set to False: only change local config
"""
option = local and '--local' or ''
run('config %s "%s" "%s"' % (option, key, value))
|
python
|
def config(key, value, local=True):
"""Set that config key to that value
Unless local is set to False: only change local config
"""
option = local and '--local' or ''
run('config %s "%s" "%s"' % (option, key, value))
|
[
"def",
"config",
"(",
"key",
",",
"value",
",",
"local",
"=",
"True",
")",
":",
"option",
"=",
"local",
"and",
"'--local'",
"or",
"''",
"run",
"(",
"'config %s \"%s\" \"%s\"'",
"%",
"(",
"option",
",",
"key",
",",
"value",
")",
")"
] |
Set that config key to that value
Unless local is set to False: only change local config
|
[
"Set",
"that",
"config",
"key",
"to",
"that",
"value"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L330-L336
|
242,514
|
jalanb/pysyte
|
pysyte/bash/git.py
|
clone
|
def clone(url, path=None, remove=True):
"""Clone a local repo from that URL to that path
If path is not given, then use the git default: same as repo name
If path is given and remove is True
then the path is removed before cloning
Because this is run from a script it is assumed that user should be Admin
so set config user values for the GitLab Admin
"""
clean = True
if path and os.path.isdir(path):
if not remove:
clean = False
else:
shutil.rmtree(path)
if clean:
stdout = run('clone %s %s' % (url, path or ''))
into = stdout.splitlines()[0].split("'")[1]
path_to_clone = os.path.realpath(into)
else:
path_to_clone = path
old_dir = _working_dirs[0]
_working_dirs[0] = path_to_clone
config('user.name', 'Release Script')
config('user.email', 'gitlab@wwts.com')
_working_dirs[0] = old_dir
return path_to_clone
|
python
|
def clone(url, path=None, remove=True):
"""Clone a local repo from that URL to that path
If path is not given, then use the git default: same as repo name
If path is given and remove is True
then the path is removed before cloning
Because this is run from a script it is assumed that user should be Admin
so set config user values for the GitLab Admin
"""
clean = True
if path and os.path.isdir(path):
if not remove:
clean = False
else:
shutil.rmtree(path)
if clean:
stdout = run('clone %s %s' % (url, path or ''))
into = stdout.splitlines()[0].split("'")[1]
path_to_clone = os.path.realpath(into)
else:
path_to_clone = path
old_dir = _working_dirs[0]
_working_dirs[0] = path_to_clone
config('user.name', 'Release Script')
config('user.email', 'gitlab@wwts.com')
_working_dirs[0] = old_dir
return path_to_clone
|
[
"def",
"clone",
"(",
"url",
",",
"path",
"=",
"None",
",",
"remove",
"=",
"True",
")",
":",
"clean",
"=",
"True",
"if",
"path",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"if",
"not",
"remove",
":",
"clean",
"=",
"False",
"else",
":",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"if",
"clean",
":",
"stdout",
"=",
"run",
"(",
"'clone %s %s'",
"%",
"(",
"url",
",",
"path",
"or",
"''",
")",
")",
"into",
"=",
"stdout",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
".",
"split",
"(",
"\"'\"",
")",
"[",
"1",
"]",
"path_to_clone",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"into",
")",
"else",
":",
"path_to_clone",
"=",
"path",
"old_dir",
"=",
"_working_dirs",
"[",
"0",
"]",
"_working_dirs",
"[",
"0",
"]",
"=",
"path_to_clone",
"config",
"(",
"'user.name'",
",",
"'Release Script'",
")",
"config",
"(",
"'user.email'",
",",
"'gitlab@wwts.com'",
")",
"_working_dirs",
"[",
"0",
"]",
"=",
"old_dir",
"return",
"path_to_clone"
] |
Clone a local repo from that URL to that path
If path is not given, then use the git default: same as repo name
If path is given and remove is True
then the path is removed before cloning
Because this is run from a script it is assumed that user should be Admin
so set config user values for the GitLab Admin
|
[
"Clone",
"a",
"local",
"repo",
"from",
"that",
"URL",
"to",
"that",
"path"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L347-L374
|
242,515
|
jalanb/pysyte
|
pysyte/bash/git.py
|
needs_abort
|
def needs_abort():
"""A command to abort an operation in progress
For example a merge, cherry-pick or rebase
If one of these operations has left the repo conflicted
then give a command to abandon the operation
"""
for line in status().splitlines():
if '--abort' in line:
for part in line.split('"'):
if '--abort' in part:
return part
elif 'All conflicts fixed but you are still merging' in line:
return 'git merge --abort'
elif 'You have unmerged paths.' in line:
return 'git merge --abort'
elif 'all conflicts fixed: run "git rebase --continue"' in line:
return 'git rebase --abort'
return None
|
python
|
def needs_abort():
"""A command to abort an operation in progress
For example a merge, cherry-pick or rebase
If one of these operations has left the repo conflicted
then give a command to abandon the operation
"""
for line in status().splitlines():
if '--abort' in line:
for part in line.split('"'):
if '--abort' in part:
return part
elif 'All conflicts fixed but you are still merging' in line:
return 'git merge --abort'
elif 'You have unmerged paths.' in line:
return 'git merge --abort'
elif 'all conflicts fixed: run "git rebase --continue"' in line:
return 'git rebase --abort'
return None
|
[
"def",
"needs_abort",
"(",
")",
":",
"for",
"line",
"in",
"status",
"(",
")",
".",
"splitlines",
"(",
")",
":",
"if",
"'--abort'",
"in",
"line",
":",
"for",
"part",
"in",
"line",
".",
"split",
"(",
"'\"'",
")",
":",
"if",
"'--abort'",
"in",
"part",
":",
"return",
"part",
"elif",
"'All conflicts fixed but you are still merging'",
"in",
"line",
":",
"return",
"'git merge --abort'",
"elif",
"'You have unmerged paths.'",
"in",
"line",
":",
"return",
"'git merge --abort'",
"elif",
"'all conflicts fixed: run \"git rebase --continue\"'",
"in",
"line",
":",
"return",
"'git rebase --abort'",
"return",
"None"
] |
A command to abort an operation in progress
For example a merge, cherry-pick or rebase
If one of these operations has left the repo conflicted
then give a command to abandon the operation
|
[
"A",
"command",
"to",
"abort",
"an",
"operation",
"in",
"progress"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L386-L404
|
242,516
|
jalanb/pysyte
|
pysyte/bash/git.py
|
show_branches
|
def show_branches(branch1, branch2):
"""Runs git show-branch between the 2 branches, parse result"""
def find_column(string):
"""Find first non space line in the prefix"""
result = 0
for c in string:
if c == ' ':
result += 1
return result
def parse_show_line(string):
"""Parse a typical line from git show-branch
>>> parse_show_line('+ [master^2] TOOLS-122 Add bashrc')
'+ ', 'master^2', 'TOOLS-122 Add bashrc'
"""
regexp = re.compile('(.*)\[(.*)] (.*)')
match = regexp.match(string)
if not match:
return None
prefix, commit, comment = match.groups()
return find_column(prefix), commit, comment
log = run('show-branch --sha1-name "%s" "%s"' % (branch1, branch2))
lines = iter(log.splitlines())
line = lines.next()
branches = {}
while line != '--':
column, branch, comment = parse_show_line(line)
branches[column] = [branch]
line = lines.next()
line = lines.next()
for line in lines:
column, commit, comment = parse_show_line(line)
branches[column].append((commit, comment))
return branches
|
python
|
def show_branches(branch1, branch2):
"""Runs git show-branch between the 2 branches, parse result"""
def find_column(string):
"""Find first non space line in the prefix"""
result = 0
for c in string:
if c == ' ':
result += 1
return result
def parse_show_line(string):
"""Parse a typical line from git show-branch
>>> parse_show_line('+ [master^2] TOOLS-122 Add bashrc')
'+ ', 'master^2', 'TOOLS-122 Add bashrc'
"""
regexp = re.compile('(.*)\[(.*)] (.*)')
match = regexp.match(string)
if not match:
return None
prefix, commit, comment = match.groups()
return find_column(prefix), commit, comment
log = run('show-branch --sha1-name "%s" "%s"' % (branch1, branch2))
lines = iter(log.splitlines())
line = lines.next()
branches = {}
while line != '--':
column, branch, comment = parse_show_line(line)
branches[column] = [branch]
line = lines.next()
line = lines.next()
for line in lines:
column, commit, comment = parse_show_line(line)
branches[column].append((commit, comment))
return branches
|
[
"def",
"show_branches",
"(",
"branch1",
",",
"branch2",
")",
":",
"def",
"find_column",
"(",
"string",
")",
":",
"\"\"\"Find first non space line in the prefix\"\"\"",
"result",
"=",
"0",
"for",
"c",
"in",
"string",
":",
"if",
"c",
"==",
"' '",
":",
"result",
"+=",
"1",
"return",
"result",
"def",
"parse_show_line",
"(",
"string",
")",
":",
"\"\"\"Parse a typical line from git show-branch\n\n >>> parse_show_line('+ [master^2] TOOLS-122 Add bashrc')\n '+ ', 'master^2', 'TOOLS-122 Add bashrc'\n \"\"\"",
"regexp",
"=",
"re",
".",
"compile",
"(",
"'(.*)\\[(.*)] (.*)'",
")",
"match",
"=",
"regexp",
".",
"match",
"(",
"string",
")",
"if",
"not",
"match",
":",
"return",
"None",
"prefix",
",",
"commit",
",",
"comment",
"=",
"match",
".",
"groups",
"(",
")",
"return",
"find_column",
"(",
"prefix",
")",
",",
"commit",
",",
"comment",
"log",
"=",
"run",
"(",
"'show-branch --sha1-name \"%s\" \"%s\"'",
"%",
"(",
"branch1",
",",
"branch2",
")",
")",
"lines",
"=",
"iter",
"(",
"log",
".",
"splitlines",
"(",
")",
")",
"line",
"=",
"lines",
".",
"next",
"(",
")",
"branches",
"=",
"{",
"}",
"while",
"line",
"!=",
"'--'",
":",
"column",
",",
"branch",
",",
"comment",
"=",
"parse_show_line",
"(",
"line",
")",
"branches",
"[",
"column",
"]",
"=",
"[",
"branch",
"]",
"line",
"=",
"lines",
".",
"next",
"(",
")",
"line",
"=",
"lines",
".",
"next",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"column",
",",
"commit",
",",
"comment",
"=",
"parse_show_line",
"(",
"line",
")",
"branches",
"[",
"column",
"]",
".",
"append",
"(",
"(",
"commit",
",",
"comment",
")",
")",
"return",
"branches"
] |
Runs git show-branch between the 2 branches, parse result
|
[
"Runs",
"git",
"show",
"-",
"branch",
"between",
"the",
"2",
"branches",
"parse",
"result"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L429-L465
|
242,517
|
jalanb/pysyte
|
pysyte/bash/git.py
|
checkout
|
def checkout(branch, quiet=False, as_path=False):
"""Check out that branch
Defaults to a quiet checkout, giving no stdout
if stdout it wanted, call with quiet = False
Defaults to checking out branches
If as_path is true, then treat "branch" like a file, i.e.
$ git checkout -- branch
All errors will pass silently, just returning False
except any messages about "you need to resolve your current index"
These indicate that the repository is not in a normal state
and action by a user is usually needed to resolve that
So the exception is allowed to rise
probably stopping the script
"""
try:
if as_path:
branch = '-- %s' % branch
run('checkout %s %s' % (quiet and '-q' or '', branch))
return True
except GitError as e:
if 'need to resolve your current index' in e.output:
raise
return False
|
python
|
def checkout(branch, quiet=False, as_path=False):
"""Check out that branch
Defaults to a quiet checkout, giving no stdout
if stdout it wanted, call with quiet = False
Defaults to checking out branches
If as_path is true, then treat "branch" like a file, i.e.
$ git checkout -- branch
All errors will pass silently, just returning False
except any messages about "you need to resolve your current index"
These indicate that the repository is not in a normal state
and action by a user is usually needed to resolve that
So the exception is allowed to rise
probably stopping the script
"""
try:
if as_path:
branch = '-- %s' % branch
run('checkout %s %s' % (quiet and '-q' or '', branch))
return True
except GitError as e:
if 'need to resolve your current index' in e.output:
raise
return False
|
[
"def",
"checkout",
"(",
"branch",
",",
"quiet",
"=",
"False",
",",
"as_path",
"=",
"False",
")",
":",
"try",
":",
"if",
"as_path",
":",
"branch",
"=",
"'-- %s'",
"%",
"branch",
"run",
"(",
"'checkout %s %s'",
"%",
"(",
"quiet",
"and",
"'-q'",
"or",
"''",
",",
"branch",
")",
")",
"return",
"True",
"except",
"GitError",
"as",
"e",
":",
"if",
"'need to resolve your current index'",
"in",
"e",
".",
"output",
":",
"raise",
"return",
"False"
] |
Check out that branch
Defaults to a quiet checkout, giving no stdout
if stdout it wanted, call with quiet = False
Defaults to checking out branches
If as_path is true, then treat "branch" like a file, i.e.
$ git checkout -- branch
All errors will pass silently, just returning False
except any messages about "you need to resolve your current index"
These indicate that the repository is not in a normal state
and action by a user is usually needed to resolve that
So the exception is allowed to rise
probably stopping the script
|
[
"Check",
"out",
"that",
"branch"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L509-L534
|
242,518
|
jalanb/pysyte
|
pysyte/bash/git.py
|
same_diffs
|
def same_diffs(commit1, commit2):
"""Whether those 2 commits have the same change
Run "git range-diff" against 2 commit ranges:
1. parent of commit1 to commit1
1. parent of commit2 to commit2
If the two produce the same diff then git will only show header lines
Header lines are prefixed like "1: ...."
Otherwise there will be lines after the header lines
(and those lines will show the difference)
"""
def range_one(commit):
"""A git commit "range" to include only one commit"""
return '%s^..%s' % (commit, commit)
output = run('range-diff %s %s' % (range_one(commit1), range_one(commit2)))
lines = output.splitlines()
for i, line in enumerate(lines, 1):
if not line.startswith('%s: ' % i):
break
return not lines[i:]
|
python
|
def same_diffs(commit1, commit2):
"""Whether those 2 commits have the same change
Run "git range-diff" against 2 commit ranges:
1. parent of commit1 to commit1
1. parent of commit2 to commit2
If the two produce the same diff then git will only show header lines
Header lines are prefixed like "1: ...."
Otherwise there will be lines after the header lines
(and those lines will show the difference)
"""
def range_one(commit):
"""A git commit "range" to include only one commit"""
return '%s^..%s' % (commit, commit)
output = run('range-diff %s %s' % (range_one(commit1), range_one(commit2)))
lines = output.splitlines()
for i, line in enumerate(lines, 1):
if not line.startswith('%s: ' % i):
break
return not lines[i:]
|
[
"def",
"same_diffs",
"(",
"commit1",
",",
"commit2",
")",
":",
"def",
"range_one",
"(",
"commit",
")",
":",
"\"\"\"A git commit \"range\" to include only one commit\"\"\"",
"return",
"'%s^..%s'",
"%",
"(",
"commit",
",",
"commit",
")",
"output",
"=",
"run",
"(",
"'range-diff %s %s'",
"%",
"(",
"range_one",
"(",
"commit1",
")",
",",
"range_one",
"(",
"commit2",
")",
")",
")",
"lines",
"=",
"output",
".",
"splitlines",
"(",
")",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
",",
"1",
")",
":",
"if",
"not",
"line",
".",
"startswith",
"(",
"'%s: '",
"%",
"i",
")",
":",
"break",
"return",
"not",
"lines",
"[",
"i",
":",
"]"
] |
Whether those 2 commits have the same change
Run "git range-diff" against 2 commit ranges:
1. parent of commit1 to commit1
1. parent of commit2 to commit2
If the two produce the same diff then git will only show header lines
Header lines are prefixed like "1: ...."
Otherwise there will be lines after the header lines
(and those lines will show the difference)
|
[
"Whether",
"those",
"2",
"commits",
"have",
"the",
"same",
"change"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L545-L566
|
242,519
|
jalanb/pysyte
|
pysyte/bash/git.py
|
renew_local_branch
|
def renew_local_branch(branch, start_point, remote=False):
"""Make a new local branch from that start_point
start_point is a git "commit-ish", e.g branch, tag, commit
If a local branch already exists it is removed
If remote is true then push the new branch to origin
"""
if branch in branches():
checkout(start_point)
delete(branch, force=True, remote=remote)
result = new_local_branch(branch, start_point)
if remote:
publish(branch)
return result
|
python
|
def renew_local_branch(branch, start_point, remote=False):
"""Make a new local branch from that start_point
start_point is a git "commit-ish", e.g branch, tag, commit
If a local branch already exists it is removed
If remote is true then push the new branch to origin
"""
if branch in branches():
checkout(start_point)
delete(branch, force=True, remote=remote)
result = new_local_branch(branch, start_point)
if remote:
publish(branch)
return result
|
[
"def",
"renew_local_branch",
"(",
"branch",
",",
"start_point",
",",
"remote",
"=",
"False",
")",
":",
"if",
"branch",
"in",
"branches",
"(",
")",
":",
"checkout",
"(",
"start_point",
")",
"delete",
"(",
"branch",
",",
"force",
"=",
"True",
",",
"remote",
"=",
"remote",
")",
"result",
"=",
"new_local_branch",
"(",
"branch",
",",
"start_point",
")",
"if",
"remote",
":",
"publish",
"(",
"branch",
")",
"return",
"result"
] |
Make a new local branch from that start_point
start_point is a git "commit-ish", e.g branch, tag, commit
If a local branch already exists it is removed
If remote is true then push the new branch to origin
|
[
"Make",
"a",
"new",
"local",
"branch",
"from",
"that",
"start_point"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L582-L596
|
242,520
|
jalanb/pysyte
|
pysyte/bash/git.py
|
publish
|
def publish(branch, full_force=False):
"""Publish that branch, i.e. push it to origin"""
checkout(branch)
try:
push('--force --set-upstream origin', branch)
except ExistingReference:
if full_force:
push('origin --delete', branch)
push('--force --set-upstream origin', branch)
|
python
|
def publish(branch, full_force=False):
"""Publish that branch, i.e. push it to origin"""
checkout(branch)
try:
push('--force --set-upstream origin', branch)
except ExistingReference:
if full_force:
push('origin --delete', branch)
push('--force --set-upstream origin', branch)
|
[
"def",
"publish",
"(",
"branch",
",",
"full_force",
"=",
"False",
")",
":",
"checkout",
"(",
"branch",
")",
"try",
":",
"push",
"(",
"'--force --set-upstream origin'",
",",
"branch",
")",
"except",
"ExistingReference",
":",
"if",
"full_force",
":",
"push",
"(",
"'origin --delete'",
",",
"branch",
")",
"push",
"(",
"'--force --set-upstream origin'",
",",
"branch",
")"
] |
Publish that branch, i.e. push it to origin
|
[
"Publish",
"that",
"branch",
"i",
".",
"e",
".",
"push",
"it",
"to",
"origin"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L615-L623
|
242,521
|
jalanb/pysyte
|
pysyte/bash/git.py
|
commit
|
def commit(message, add=False, quiet=False):
"""Commit with that message and return the SHA1 of the commit
If add is truish then "$ git add ." first
"""
if add:
run('add .')
try:
stdout = run('commit -m %r' % str(message), quiet=quiet)
except GitError as e:
s = str(e)
if 'nothing to commit' in s or 'no changes added to commit' in s:
raise EmptyCommit(*e.inits())
raise
return re.split('[ \]]', stdout.splitlines()[0])[1]
|
python
|
def commit(message, add=False, quiet=False):
"""Commit with that message and return the SHA1 of the commit
If add is truish then "$ git add ." first
"""
if add:
run('add .')
try:
stdout = run('commit -m %r' % str(message), quiet=quiet)
except GitError as e:
s = str(e)
if 'nothing to commit' in s or 'no changes added to commit' in s:
raise EmptyCommit(*e.inits())
raise
return re.split('[ \]]', stdout.splitlines()[0])[1]
|
[
"def",
"commit",
"(",
"message",
",",
"add",
"=",
"False",
",",
"quiet",
"=",
"False",
")",
":",
"if",
"add",
":",
"run",
"(",
"'add .'",
")",
"try",
":",
"stdout",
"=",
"run",
"(",
"'commit -m %r'",
"%",
"str",
"(",
"message",
")",
",",
"quiet",
"=",
"quiet",
")",
"except",
"GitError",
"as",
"e",
":",
"s",
"=",
"str",
"(",
"e",
")",
"if",
"'nothing to commit'",
"in",
"s",
"or",
"'no changes added to commit'",
"in",
"s",
":",
"raise",
"EmptyCommit",
"(",
"*",
"e",
".",
"inits",
"(",
")",
")",
"raise",
"return",
"re",
".",
"split",
"(",
"'[ \\]]'",
",",
"stdout",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
")",
"[",
"1",
"]"
] |
Commit with that message and return the SHA1 of the commit
If add is truish then "$ git add ." first
|
[
"Commit",
"with",
"that",
"message",
"and",
"return",
"the",
"SHA1",
"of",
"the",
"commit"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L646-L660
|
242,522
|
jalanb/pysyte
|
pysyte/bash/git.py
|
pull
|
def pull(rebase=True, refspec=None):
"""Pull refspec from remote repository to local
If refspec is left as None, then pull current branch
The '--rebase' option is used unless rebase is set to false
"""
options = rebase and '--rebase' or ''
output = run('pull %s %s' % (options, refspec or ''))
return not re.search('up.to.date', output)
|
python
|
def pull(rebase=True, refspec=None):
"""Pull refspec from remote repository to local
If refspec is left as None, then pull current branch
The '--rebase' option is used unless rebase is set to false
"""
options = rebase and '--rebase' or ''
output = run('pull %s %s' % (options, refspec or ''))
return not re.search('up.to.date', output)
|
[
"def",
"pull",
"(",
"rebase",
"=",
"True",
",",
"refspec",
"=",
"None",
")",
":",
"options",
"=",
"rebase",
"and",
"'--rebase'",
"or",
"''",
"output",
"=",
"run",
"(",
"'pull %s %s'",
"%",
"(",
"options",
",",
"refspec",
"or",
"''",
")",
")",
"return",
"not",
"re",
".",
"search",
"(",
"'up.to.date'",
",",
"output",
")"
] |
Pull refspec from remote repository to local
If refspec is left as None, then pull current branch
The '--rebase' option is used unless rebase is set to false
|
[
"Pull",
"refspec",
"from",
"remote",
"repository",
"to",
"local"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L663-L671
|
242,523
|
jalanb/pysyte
|
pysyte/bash/git.py
|
rebase
|
def rebase(upstream, branch=None):
"""Rebase branch onto upstream
If branch is empty, use current branch
"""
rebase_branch = branch and branch or current_branch()
with git_continuer(run, 'rebase --continue', no_edit=True):
stdout = run('rebase %s %s' % (upstream, rebase_branch))
return 'Applying' in stdout
|
python
|
def rebase(upstream, branch=None):
"""Rebase branch onto upstream
If branch is empty, use current branch
"""
rebase_branch = branch and branch or current_branch()
with git_continuer(run, 'rebase --continue', no_edit=True):
stdout = run('rebase %s %s' % (upstream, rebase_branch))
return 'Applying' in stdout
|
[
"def",
"rebase",
"(",
"upstream",
",",
"branch",
"=",
"None",
")",
":",
"rebase_branch",
"=",
"branch",
"and",
"branch",
"or",
"current_branch",
"(",
")",
"with",
"git_continuer",
"(",
"run",
",",
"'rebase --continue'",
",",
"no_edit",
"=",
"True",
")",
":",
"stdout",
"=",
"run",
"(",
"'rebase %s %s'",
"%",
"(",
"upstream",
",",
"rebase_branch",
")",
")",
"return",
"'Applying'",
"in",
"stdout"
] |
Rebase branch onto upstream
If branch is empty, use current branch
|
[
"Rebase",
"branch",
"onto",
"upstream"
] |
4e278101943d1ceb1a6bcaf6ddc72052ecf13114
|
https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/bash/git.py#L762-L771
|
242,524
|
larsks/thecache
|
thecache/cache.py
|
tempfile_writer
|
def tempfile_writer(target):
'''write cache data to a temporary location. when writing is
complete, rename the file to the actual location. delete
the temporary file on any error'''
tmp = target.parent / ('_%s' % target.name)
try:
with tmp.open('wb') as fd:
yield fd
except:
tmp.unlink()
raise
LOG.debug('rename %s -> %s', tmp, target)
tmp.rename(target)
|
python
|
def tempfile_writer(target):
'''write cache data to a temporary location. when writing is
complete, rename the file to the actual location. delete
the temporary file on any error'''
tmp = target.parent / ('_%s' % target.name)
try:
with tmp.open('wb') as fd:
yield fd
except:
tmp.unlink()
raise
LOG.debug('rename %s -> %s', tmp, target)
tmp.rename(target)
|
[
"def",
"tempfile_writer",
"(",
"target",
")",
":",
"tmp",
"=",
"target",
".",
"parent",
"/",
"(",
"'_%s'",
"%",
"target",
".",
"name",
")",
"try",
":",
"with",
"tmp",
".",
"open",
"(",
"'wb'",
")",
"as",
"fd",
":",
"yield",
"fd",
"except",
":",
"tmp",
".",
"unlink",
"(",
")",
"raise",
"LOG",
".",
"debug",
"(",
"'rename %s -> %s'",
",",
"tmp",
",",
"target",
")",
"tmp",
".",
"rename",
"(",
"target",
")"
] |
write cache data to a temporary location. when writing is
complete, rename the file to the actual location. delete
the temporary file on any error
|
[
"write",
"cache",
"data",
"to",
"a",
"temporary",
"location",
".",
"when",
"writing",
"is",
"complete",
"rename",
"the",
"file",
"to",
"the",
"actual",
"location",
".",
"delete",
"the",
"temporary",
"file",
"on",
"any",
"error"
] |
e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0
|
https://github.com/larsks/thecache/blob/e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0/thecache/cache.py#L46-L58
|
242,525
|
larsks/thecache
|
thecache/cache.py
|
Cache.xform_key
|
def xform_key(self, key):
'''we transform cache keys by taking their sha1 hash so that
we don't need to worry about cache keys containing invalid
characters'''
newkey = hashlib.sha1(key.encode('utf-8'))
return newkey.hexdigest()
|
python
|
def xform_key(self, key):
'''we transform cache keys by taking their sha1 hash so that
we don't need to worry about cache keys containing invalid
characters'''
newkey = hashlib.sha1(key.encode('utf-8'))
return newkey.hexdigest()
|
[
"def",
"xform_key",
"(",
"self",
",",
"key",
")",
":",
"newkey",
"=",
"hashlib",
".",
"sha1",
"(",
"key",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"return",
"newkey",
".",
"hexdigest",
"(",
")"
] |
we transform cache keys by taking their sha1 hash so that
we don't need to worry about cache keys containing invalid
characters
|
[
"we",
"transform",
"cache",
"keys",
"by",
"taking",
"their",
"sha1",
"hash",
"so",
"that",
"we",
"don",
"t",
"need",
"to",
"worry",
"about",
"cache",
"keys",
"containing",
"invalid",
"characters"
] |
e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0
|
https://github.com/larsks/thecache/blob/e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0/thecache/cache.py#L104-L110
|
242,526
|
larsks/thecache
|
thecache/cache.py
|
Cache.invalidate
|
def invalidate(self, key):
'''Clear an item from the cache'''
path = self.path(self.xform_key(key))
try:
LOG.debug('invalidate %s (%s)', key, path)
path.unlink()
except OSError:
pass
|
python
|
def invalidate(self, key):
'''Clear an item from the cache'''
path = self.path(self.xform_key(key))
try:
LOG.debug('invalidate %s (%s)', key, path)
path.unlink()
except OSError:
pass
|
[
"def",
"invalidate",
"(",
"self",
",",
"key",
")",
":",
"path",
"=",
"self",
".",
"path",
"(",
"self",
".",
"xform_key",
"(",
"key",
")",
")",
"try",
":",
"LOG",
".",
"debug",
"(",
"'invalidate %s (%s)'",
",",
"key",
",",
"path",
")",
"path",
".",
"unlink",
"(",
")",
"except",
"OSError",
":",
"pass"
] |
Clear an item from the cache
|
[
"Clear",
"an",
"item",
"from",
"the",
"cache"
] |
e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0
|
https://github.com/larsks/thecache/blob/e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0/thecache/cache.py#L112-L119
|
242,527
|
larsks/thecache
|
thecache/cache.py
|
Cache.invalidate_all
|
def invalidate_all(self):
'''Clear all items from the cache'''
LOG.debug('clearing cache')
appcache = str(self.get_app_cache())
for dirpath, dirnames, filenames in os.walk(appcache):
for name in filenames:
try:
pathlib.Path(dirpath, name).unlink()
except OSError:
pass
|
python
|
def invalidate_all(self):
'''Clear all items from the cache'''
LOG.debug('clearing cache')
appcache = str(self.get_app_cache())
for dirpath, dirnames, filenames in os.walk(appcache):
for name in filenames:
try:
pathlib.Path(dirpath, name).unlink()
except OSError:
pass
|
[
"def",
"invalidate_all",
"(",
"self",
")",
":",
"LOG",
".",
"debug",
"(",
"'clearing cache'",
")",
"appcache",
"=",
"str",
"(",
"self",
".",
"get_app_cache",
"(",
")",
")",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"appcache",
")",
":",
"for",
"name",
"in",
"filenames",
":",
"try",
":",
"pathlib",
".",
"Path",
"(",
"dirpath",
",",
"name",
")",
".",
"unlink",
"(",
")",
"except",
"OSError",
":",
"pass"
] |
Clear all items from the cache
|
[
"Clear",
"all",
"items",
"from",
"the",
"cache"
] |
e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0
|
https://github.com/larsks/thecache/blob/e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0/thecache/cache.py#L121-L131
|
242,528
|
larsks/thecache
|
thecache/cache.py
|
Cache.store_iter
|
def store_iter(self, key, content):
'''stores content in the cache by iterating over
content'''
cachekey = self.xform_key(key)
path = self.path(cachekey)
with tempfile_writer(path) as fd:
for data in content:
LOG.debug('writing chunk of %d bytes for %s',
len(data), key)
fd.write(data)
LOG.debug('%s stored in cache', key)
|
python
|
def store_iter(self, key, content):
'''stores content in the cache by iterating over
content'''
cachekey = self.xform_key(key)
path = self.path(cachekey)
with tempfile_writer(path) as fd:
for data in content:
LOG.debug('writing chunk of %d bytes for %s',
len(data), key)
fd.write(data)
LOG.debug('%s stored in cache', key)
|
[
"def",
"store_iter",
"(",
"self",
",",
"key",
",",
"content",
")",
":",
"cachekey",
"=",
"self",
".",
"xform_key",
"(",
"key",
")",
"path",
"=",
"self",
".",
"path",
"(",
"cachekey",
")",
"with",
"tempfile_writer",
"(",
"path",
")",
"as",
"fd",
":",
"for",
"data",
"in",
"content",
":",
"LOG",
".",
"debug",
"(",
"'writing chunk of %d bytes for %s'",
",",
"len",
"(",
"data",
")",
",",
"key",
")",
"fd",
".",
"write",
"(",
"data",
")",
"LOG",
".",
"debug",
"(",
"'%s stored in cache'",
",",
"key",
")"
] |
stores content in the cache by iterating over
content
|
[
"stores",
"content",
"in",
"the",
"cache",
"by",
"iterating",
"over",
"content"
] |
e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0
|
https://github.com/larsks/thecache/blob/e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0/thecache/cache.py#L133-L144
|
242,529
|
larsks/thecache
|
thecache/cache.py
|
Cache.store_lines
|
def store_lines(self, key, content):
'''like store_iter, but appends a newline to each chunk of
content'''
return self.store_iter(
key,
(data + '\n'.encode('utf-8') for data in content))
|
python
|
def store_lines(self, key, content):
'''like store_iter, but appends a newline to each chunk of
content'''
return self.store_iter(
key,
(data + '\n'.encode('utf-8') for data in content))
|
[
"def",
"store_lines",
"(",
"self",
",",
"key",
",",
"content",
")",
":",
"return",
"self",
".",
"store_iter",
"(",
"key",
",",
"(",
"data",
"+",
"'\\n'",
".",
"encode",
"(",
"'utf-8'",
")",
"for",
"data",
"in",
"content",
")",
")"
] |
like store_iter, but appends a newline to each chunk of
content
|
[
"like",
"store_iter",
"but",
"appends",
"a",
"newline",
"to",
"each",
"chunk",
"of",
"content"
] |
e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0
|
https://github.com/larsks/thecache/blob/e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0/thecache/cache.py#L146-L151
|
242,530
|
larsks/thecache
|
thecache/cache.py
|
Cache.load_fd
|
def load_fd(self, key, noexpire=False):
'''Look up an item in the cache and return an open file
descriptor for the object. It is the caller's responsibility
to close the file descriptor.'''
cachekey = self.xform_key(key)
path = self.path(cachekey)
try:
stat = path.stat()
if not noexpire and stat.st_mtime < time.time() - self.lifetime:
LOG.debug('%s has expired', key)
path.unlink()
raise KeyError(key)
LOG.debug('%s found in cache', key)
return path.open('rb')
except OSError:
LOG.debug('%s not found in cache', key)
raise KeyError(key)
|
python
|
def load_fd(self, key, noexpire=False):
'''Look up an item in the cache and return an open file
descriptor for the object. It is the caller's responsibility
to close the file descriptor.'''
cachekey = self.xform_key(key)
path = self.path(cachekey)
try:
stat = path.stat()
if not noexpire and stat.st_mtime < time.time() - self.lifetime:
LOG.debug('%s has expired', key)
path.unlink()
raise KeyError(key)
LOG.debug('%s found in cache', key)
return path.open('rb')
except OSError:
LOG.debug('%s not found in cache', key)
raise KeyError(key)
|
[
"def",
"load_fd",
"(",
"self",
",",
"key",
",",
"noexpire",
"=",
"False",
")",
":",
"cachekey",
"=",
"self",
".",
"xform_key",
"(",
"key",
")",
"path",
"=",
"self",
".",
"path",
"(",
"cachekey",
")",
"try",
":",
"stat",
"=",
"path",
".",
"stat",
"(",
")",
"if",
"not",
"noexpire",
"and",
"stat",
".",
"st_mtime",
"<",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"lifetime",
":",
"LOG",
".",
"debug",
"(",
"'%s has expired'",
",",
"key",
")",
"path",
".",
"unlink",
"(",
")",
"raise",
"KeyError",
"(",
"key",
")",
"LOG",
".",
"debug",
"(",
"'%s found in cache'",
",",
"key",
")",
"return",
"path",
".",
"open",
"(",
"'rb'",
")",
"except",
"OSError",
":",
"LOG",
".",
"debug",
"(",
"'%s not found in cache'",
",",
"key",
")",
"raise",
"KeyError",
"(",
"key",
")"
] |
Look up an item in the cache and return an open file
descriptor for the object. It is the caller's responsibility
to close the file descriptor.
|
[
"Look",
"up",
"an",
"item",
"in",
"the",
"cache",
"and",
"return",
"an",
"open",
"file",
"descriptor",
"for",
"the",
"object",
".",
"It",
"is",
"the",
"caller",
"s",
"responsibility",
"to",
"close",
"the",
"file",
"descriptor",
"."
] |
e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0
|
https://github.com/larsks/thecache/blob/e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0/thecache/cache.py#L174-L193
|
242,531
|
larsks/thecache
|
thecache/cache.py
|
Cache.load_lines
|
def load_lines(self, key, noexpire=None):
'''Look up up an item in the cache and return a line iterator.
The underlying file will be closed once all lines have been
consumed.'''
return line_iterator(self.load_fd(key, noexpire=noexpire))
|
python
|
def load_lines(self, key, noexpire=None):
'''Look up up an item in the cache and return a line iterator.
The underlying file will be closed once all lines have been
consumed.'''
return line_iterator(self.load_fd(key, noexpire=noexpire))
|
[
"def",
"load_lines",
"(",
"self",
",",
"key",
",",
"noexpire",
"=",
"None",
")",
":",
"return",
"line_iterator",
"(",
"self",
".",
"load_fd",
"(",
"key",
",",
"noexpire",
"=",
"noexpire",
")",
")"
] |
Look up up an item in the cache and return a line iterator.
The underlying file will be closed once all lines have been
consumed.
|
[
"Look",
"up",
"up",
"an",
"item",
"in",
"the",
"cache",
"and",
"return",
"a",
"line",
"iterator",
".",
"The",
"underlying",
"file",
"will",
"be",
"closed",
"once",
"all",
"lines",
"have",
"been",
"consumed",
"."
] |
e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0
|
https://github.com/larsks/thecache/blob/e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0/thecache/cache.py#L195-L199
|
242,532
|
larsks/thecache
|
thecache/cache.py
|
Cache.load_iter
|
def load_iter(self, key, chunksize=None, noexpire=None):
'''Lookup an item in the cache and return an iterator
that reads chunksize bytes of data at a time. The underlying
file will be closed when all data has been read'''
return chunk_iterator(self.load_fd(key, noexpire=noexpire),
chunksize=chunksize)
|
python
|
def load_iter(self, key, chunksize=None, noexpire=None):
'''Lookup an item in the cache and return an iterator
that reads chunksize bytes of data at a time. The underlying
file will be closed when all data has been read'''
return chunk_iterator(self.load_fd(key, noexpire=noexpire),
chunksize=chunksize)
|
[
"def",
"load_iter",
"(",
"self",
",",
"key",
",",
"chunksize",
"=",
"None",
",",
"noexpire",
"=",
"None",
")",
":",
"return",
"chunk_iterator",
"(",
"self",
".",
"load_fd",
"(",
"key",
",",
"noexpire",
"=",
"noexpire",
")",
",",
"chunksize",
"=",
"chunksize",
")"
] |
Lookup an item in the cache and return an iterator
that reads chunksize bytes of data at a time. The underlying
file will be closed when all data has been read
|
[
"Lookup",
"an",
"item",
"in",
"the",
"cache",
"and",
"return",
"an",
"iterator",
"that",
"reads",
"chunksize",
"bytes",
"of",
"data",
"at",
"a",
"time",
".",
"The",
"underlying",
"file",
"will",
"be",
"closed",
"when",
"all",
"data",
"has",
"been",
"read"
] |
e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0
|
https://github.com/larsks/thecache/blob/e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0/thecache/cache.py#L201-L206
|
242,533
|
larsks/thecache
|
thecache/cache.py
|
Cache.load
|
def load(self, key, noexpire=None):
'''Lookup an item in the cache and return the raw content of
the file as a string.'''
with self.load_fd(key, noexpire=noexpire) as fd:
return fd.read()
|
python
|
def load(self, key, noexpire=None):
'''Lookup an item in the cache and return the raw content of
the file as a string.'''
with self.load_fd(key, noexpire=noexpire) as fd:
return fd.read()
|
[
"def",
"load",
"(",
"self",
",",
"key",
",",
"noexpire",
"=",
"None",
")",
":",
"with",
"self",
".",
"load_fd",
"(",
"key",
",",
"noexpire",
"=",
"noexpire",
")",
"as",
"fd",
":",
"return",
"fd",
".",
"read",
"(",
")"
] |
Lookup an item in the cache and return the raw content of
the file as a string.
|
[
"Lookup",
"an",
"item",
"in",
"the",
"cache",
"and",
"return",
"the",
"raw",
"content",
"of",
"the",
"file",
"as",
"a",
"string",
"."
] |
e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0
|
https://github.com/larsks/thecache/blob/e535f91031a7f92f19b5ff6fe2a1a03c7680e9e0/thecache/cache.py#L208-L212
|
242,534
|
jerith/txTwitter
|
txtwitter/twitter.py
|
set_bool_param
|
def set_bool_param(params, name, value):
"""
Set a boolean parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param bool value:
The value of the parameter. If ``None``, the field will not be set. If
``True`` or ``False``, the relevant field in ``params`` will be set to
``'true'`` or ``'false'``. Any other value will raise a `ValueError`.
:returns: ``None``
"""
if value is None:
return
if value is True:
params[name] = 'true'
elif value is False:
params[name] = 'false'
else:
raise ValueError("Parameter '%s' must be boolean or None, got %r." % (
name, value))
|
python
|
def set_bool_param(params, name, value):
"""
Set a boolean parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param bool value:
The value of the parameter. If ``None``, the field will not be set. If
``True`` or ``False``, the relevant field in ``params`` will be set to
``'true'`` or ``'false'``. Any other value will raise a `ValueError`.
:returns: ``None``
"""
if value is None:
return
if value is True:
params[name] = 'true'
elif value is False:
params[name] = 'false'
else:
raise ValueError("Parameter '%s' must be boolean or None, got %r." % (
name, value))
|
[
"def",
"set_bool_param",
"(",
"params",
",",
"name",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"if",
"value",
"is",
"True",
":",
"params",
"[",
"name",
"]",
"=",
"'true'",
"elif",
"value",
"is",
"False",
":",
"params",
"[",
"name",
"]",
"=",
"'false'",
"else",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must be boolean or None, got %r.\"",
"%",
"(",
"name",
",",
"value",
")",
")"
] |
Set a boolean parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param bool value:
The value of the parameter. If ``None``, the field will not be set. If
``True`` or ``False``, the relevant field in ``params`` will be set to
``'true'`` or ``'false'``. Any other value will raise a `ValueError`.
:returns: ``None``
|
[
"Set",
"a",
"boolean",
"parameter",
"if",
"applicable",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L34-L58
|
242,535
|
jerith/txTwitter
|
txtwitter/twitter.py
|
set_str_param
|
def set_str_param(params, name, value):
"""
Set a string parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of ``str``, the relevant field will be set. If an instance
of ``unicode``, the relevant field will be set to the UTF-8 encoding.
Any other value will raise a `ValueError`.
:returns: ``None``
"""
if value is None:
return
if isinstance(value, str):
params[name] = value
elif isinstance(value, unicode):
params[name] = value.encode('utf-8')
else:
raise ValueError("Parameter '%s' must be a string or None, got %r." % (
name, value))
|
python
|
def set_str_param(params, name, value):
"""
Set a string parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of ``str``, the relevant field will be set. If an instance
of ``unicode``, the relevant field will be set to the UTF-8 encoding.
Any other value will raise a `ValueError`.
:returns: ``None``
"""
if value is None:
return
if isinstance(value, str):
params[name] = value
elif isinstance(value, unicode):
params[name] = value.encode('utf-8')
else:
raise ValueError("Parameter '%s' must be a string or None, got %r." % (
name, value))
|
[
"def",
"set_str_param",
"(",
"params",
",",
"name",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"params",
"[",
"name",
"]",
"=",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"params",
"[",
"name",
"]",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must be a string or None, got %r.\"",
"%",
"(",
"name",
",",
"value",
")",
")"
] |
Set a string parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of ``str``, the relevant field will be set. If an instance
of ``unicode``, the relevant field will be set to the UTF-8 encoding.
Any other value will raise a `ValueError`.
:returns: ``None``
|
[
"Set",
"a",
"string",
"parameter",
"if",
"applicable",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L61-L86
|
242,536
|
jerith/txTwitter
|
txtwitter/twitter.py
|
set_float_param
|
def set_float_param(params, name, value, min=None, max=None):
"""
Set a float parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param float value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of a numeric type or a string that can be turned into a
``float``, the relevant field will be set. Any other value will raise a
`ValueError`.
:param float min:
If provided, values less than this will raise ``ValueError``.
:param float max:
If provided, values greater than this will raise ``ValueError``.
:returns: ``None``
"""
if value is None:
return
try:
value = float(str(value))
except:
raise ValueError(
"Parameter '%s' must be numeric (or a numeric string) or None,"
" got %r." % (name, value))
if min is not None and value < min:
raise ValueError(
"Parameter '%s' must not be less than %r, got %r." % (
name, min, value))
if max is not None and value > max:
raise ValueError(
"Parameter '%s' must not be greater than %r, got %r." % (
name, min, value))
params[name] = str(value)
|
python
|
def set_float_param(params, name, value, min=None, max=None):
"""
Set a float parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param float value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of a numeric type or a string that can be turned into a
``float``, the relevant field will be set. Any other value will raise a
`ValueError`.
:param float min:
If provided, values less than this will raise ``ValueError``.
:param float max:
If provided, values greater than this will raise ``ValueError``.
:returns: ``None``
"""
if value is None:
return
try:
value = float(str(value))
except:
raise ValueError(
"Parameter '%s' must be numeric (or a numeric string) or None,"
" got %r." % (name, value))
if min is not None and value < min:
raise ValueError(
"Parameter '%s' must not be less than %r, got %r." % (
name, min, value))
if max is not None and value > max:
raise ValueError(
"Parameter '%s' must not be greater than %r, got %r." % (
name, min, value))
params[name] = str(value)
|
[
"def",
"set_float_param",
"(",
"params",
",",
"name",
",",
"value",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"value",
"=",
"float",
"(",
"str",
"(",
"value",
")",
")",
"except",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must be numeric (or a numeric string) or None,\"",
"\" got %r.\"",
"%",
"(",
"name",
",",
"value",
")",
")",
"if",
"min",
"is",
"not",
"None",
"and",
"value",
"<",
"min",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must not be less than %r, got %r.\"",
"%",
"(",
"name",
",",
"min",
",",
"value",
")",
")",
"if",
"max",
"is",
"not",
"None",
"and",
"value",
">",
"max",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must not be greater than %r, got %r.\"",
"%",
"(",
"name",
",",
"min",
",",
"value",
")",
")",
"params",
"[",
"name",
"]",
"=",
"str",
"(",
"value",
")"
] |
Set a float parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param float value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of a numeric type or a string that can be turned into a
``float``, the relevant field will be set. Any other value will raise a
`ValueError`.
:param float min:
If provided, values less than this will raise ``ValueError``.
:param float max:
If provided, values greater than this will raise ``ValueError``.
:returns: ``None``
|
[
"Set",
"a",
"float",
"parameter",
"if",
"applicable",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L89-L129
|
242,537
|
jerith/txTwitter
|
txtwitter/twitter.py
|
set_int_param
|
def set_int_param(params, name, value, min=None, max=None):
"""
Set a int parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param int value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of a numeric type or a string that can be turned into a
``int``, the relevant field will be set. Any other value will raise a
`ValueError`.
:param int min:
If provided, values less than this will raise ``ValueError``.
:param int max:
If provided, values greater than this will raise ``ValueError``.
:returns: ``None``
"""
if value is None:
return
try:
value = int(str(value))
except:
raise ValueError(
"Parameter '%s' must be an integer (or a string representation of"
" an integer) or None, got %r." % (name, value))
if min is not None and value < min:
raise ValueError(
"Parameter '%s' must not be less than %r, got %r." % (
name, min, value))
if max is not None and value > max:
raise ValueError(
"Parameter '%s' must not be greater than %r, got %r." % (
name, min, value))
params[name] = str(value)
|
python
|
def set_int_param(params, name, value, min=None, max=None):
"""
Set a int parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param int value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of a numeric type or a string that can be turned into a
``int``, the relevant field will be set. Any other value will raise a
`ValueError`.
:param int min:
If provided, values less than this will raise ``ValueError``.
:param int max:
If provided, values greater than this will raise ``ValueError``.
:returns: ``None``
"""
if value is None:
return
try:
value = int(str(value))
except:
raise ValueError(
"Parameter '%s' must be an integer (or a string representation of"
" an integer) or None, got %r." % (name, value))
if min is not None and value < min:
raise ValueError(
"Parameter '%s' must not be less than %r, got %r." % (
name, min, value))
if max is not None and value > max:
raise ValueError(
"Parameter '%s' must not be greater than %r, got %r." % (
name, min, value))
params[name] = str(value)
|
[
"def",
"set_int_param",
"(",
"params",
",",
"name",
",",
"value",
",",
"min",
"=",
"None",
",",
"max",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"value",
"=",
"int",
"(",
"str",
"(",
"value",
")",
")",
"except",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must be an integer (or a string representation of\"",
"\" an integer) or None, got %r.\"",
"%",
"(",
"name",
",",
"value",
")",
")",
"if",
"min",
"is",
"not",
"None",
"and",
"value",
"<",
"min",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must not be less than %r, got %r.\"",
"%",
"(",
"name",
",",
"min",
",",
"value",
")",
")",
"if",
"max",
"is",
"not",
"None",
"and",
"value",
">",
"max",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must not be greater than %r, got %r.\"",
"%",
"(",
"name",
",",
"min",
",",
"value",
")",
")",
"params",
"[",
"name",
"]",
"=",
"str",
"(",
"value",
")"
] |
Set a int parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param int value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of a numeric type or a string that can be turned into a
``int``, the relevant field will be set. Any other value will raise a
`ValueError`.
:param int min:
If provided, values less than this will raise ``ValueError``.
:param int max:
If provided, values greater than this will raise ``ValueError``.
:returns: ``None``
|
[
"Set",
"a",
"int",
"parameter",
"if",
"applicable",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L132-L172
|
242,538
|
jerith/txTwitter
|
txtwitter/twitter.py
|
set_list_param
|
def set_list_param(params, name, value, min_len=None, max_len=None):
"""
Set a list parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param list value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of ``set``, ``tuple``, or type that can be turned into
a ``list``, the relevant field will be set. If ``dict``, will raise
``ValueError``. Any other value will raise a ``ValueError``.
:param int min_len:
If provided, values shorter than this will raise ``ValueError``.
:param int max_len:
If provided, values longer than this will raise ``ValueError``.
"""
if value is None:
return
if type(value) is dict:
raise ValueError(
"Parameter '%s' cannot be a dict." % name)
try:
value = list(value)
except:
raise ValueError(
"Parameter '%s' must be a list (or a type that can be turned into"
"a list) or None, got %r." % (name, value))
if min_len is not None and len(value) < min_len:
raise ValueError(
"Parameter '%s' must not be shorter than %r, got %r." % (
name, min_len, value))
if max_len is not None and len(value) > max_len:
raise ValueError(
"Parameter '%s' must not be longer than %r, got %r." % (
name, max_len, value))
list_str = ''
for item in value:
list_str += '%s,' % item
set_str_param(params, name, list_str)
|
python
|
def set_list_param(params, name, value, min_len=None, max_len=None):
"""
Set a list parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param list value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of ``set``, ``tuple``, or type that can be turned into
a ``list``, the relevant field will be set. If ``dict``, will raise
``ValueError``. Any other value will raise a ``ValueError``.
:param int min_len:
If provided, values shorter than this will raise ``ValueError``.
:param int max_len:
If provided, values longer than this will raise ``ValueError``.
"""
if value is None:
return
if type(value) is dict:
raise ValueError(
"Parameter '%s' cannot be a dict." % name)
try:
value = list(value)
except:
raise ValueError(
"Parameter '%s' must be a list (or a type that can be turned into"
"a list) or None, got %r." % (name, value))
if min_len is not None and len(value) < min_len:
raise ValueError(
"Parameter '%s' must not be shorter than %r, got %r." % (
name, min_len, value))
if max_len is not None and len(value) > max_len:
raise ValueError(
"Parameter '%s' must not be longer than %r, got %r." % (
name, max_len, value))
list_str = ''
for item in value:
list_str += '%s,' % item
set_str_param(params, name, list_str)
|
[
"def",
"set_list_param",
"(",
"params",
",",
"name",
",",
"value",
",",
"min_len",
"=",
"None",
",",
"max_len",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"if",
"type",
"(",
"value",
")",
"is",
"dict",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' cannot be a dict.\"",
"%",
"name",
")",
"try",
":",
"value",
"=",
"list",
"(",
"value",
")",
"except",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must be a list (or a type that can be turned into\"",
"\"a list) or None, got %r.\"",
"%",
"(",
"name",
",",
"value",
")",
")",
"if",
"min_len",
"is",
"not",
"None",
"and",
"len",
"(",
"value",
")",
"<",
"min_len",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must not be shorter than %r, got %r.\"",
"%",
"(",
"name",
",",
"min_len",
",",
"value",
")",
")",
"if",
"max_len",
"is",
"not",
"None",
"and",
"len",
"(",
"value",
")",
">",
"max_len",
":",
"raise",
"ValueError",
"(",
"\"Parameter '%s' must not be longer than %r, got %r.\"",
"%",
"(",
"name",
",",
"max_len",
",",
"value",
")",
")",
"list_str",
"=",
"''",
"for",
"item",
"in",
"value",
":",
"list_str",
"+=",
"'%s,'",
"%",
"item",
"set_str_param",
"(",
"params",
",",
"name",
",",
"list_str",
")"
] |
Set a list parameter if applicable.
:param dict params: A dict containing API call parameters.
:param str name: The name of the parameter to set.
:param list value:
The value of the parameter. If ``None``, the field will not be set. If
an instance of ``set``, ``tuple``, or type that can be turned into
a ``list``, the relevant field will be set. If ``dict``, will raise
``ValueError``. Any other value will raise a ``ValueError``.
:param int min_len:
If provided, values shorter than this will raise ``ValueError``.
:param int max_len:
If provided, values longer than this will raise ``ValueError``.
|
[
"Set",
"a",
"list",
"parameter",
"if",
"applicable",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L175-L221
|
242,539
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.statuses_user_timeline
|
def statuses_user_timeline(self, user_id=None, screen_name=None,
since_id=None, count=None, max_id=None,
trim_user=None, exclude_replies=None,
contributor_details=None,
include_rts=None):
"""
Returns a list of the most recent tweets posted by the specified user.
https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
Either ``user_id`` or ``screen_name`` must be provided.
:param str user_id:
The ID of the user to return tweets for.
:param str screen_name:
The screen name of the user to return tweets for.
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. Tweets newer than this may not be returned due to
certain API limits.
:param int count:
Specifies the number of tweets to try and retrieve, up to a maximum
of 200.
:param str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:param bool exclude_replies:
When set to ``True``, replies will not appear in the timeline.
:param bool contributor_details:
This parameter enhances the contributors element of the status
response to include the screen_name of the contributor. By default
only the user_id of the contributor is included.
:param bool include_rts:
When set to ``False``, retweets will not appear in the timeline.
:returns: A list of tweet dicts.
"""
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
set_str_param(params, 'since_id', since_id)
set_int_param(params, 'count', count)
set_str_param(params, 'max_id', max_id)
set_bool_param(params, 'trim_user', trim_user)
set_bool_param(params, 'exclude_replies', exclude_replies)
set_bool_param(params, 'contributor_details', contributor_details)
set_bool_param(params, 'include_rts', include_rts)
return self._get_api('statuses/user_timeline.json', params)
|
python
|
def statuses_user_timeline(self, user_id=None, screen_name=None,
since_id=None, count=None, max_id=None,
trim_user=None, exclude_replies=None,
contributor_details=None,
include_rts=None):
"""
Returns a list of the most recent tweets posted by the specified user.
https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
Either ``user_id`` or ``screen_name`` must be provided.
:param str user_id:
The ID of the user to return tweets for.
:param str screen_name:
The screen name of the user to return tweets for.
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. Tweets newer than this may not be returned due to
certain API limits.
:param int count:
Specifies the number of tweets to try and retrieve, up to a maximum
of 200.
:param str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:param bool exclude_replies:
When set to ``True``, replies will not appear in the timeline.
:param bool contributor_details:
This parameter enhances the contributors element of the status
response to include the screen_name of the contributor. By default
only the user_id of the contributor is included.
:param bool include_rts:
When set to ``False``, retweets will not appear in the timeline.
:returns: A list of tweet dicts.
"""
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
set_str_param(params, 'since_id', since_id)
set_int_param(params, 'count', count)
set_str_param(params, 'max_id', max_id)
set_bool_param(params, 'trim_user', trim_user)
set_bool_param(params, 'exclude_replies', exclude_replies)
set_bool_param(params, 'contributor_details', contributor_details)
set_bool_param(params, 'include_rts', include_rts)
return self._get_api('statuses/user_timeline.json', params)
|
[
"def",
"statuses_user_timeline",
"(",
"self",
",",
"user_id",
"=",
"None",
",",
"screen_name",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"count",
"=",
"None",
",",
"max_id",
"=",
"None",
",",
"trim_user",
"=",
"None",
",",
"exclude_replies",
"=",
"None",
",",
"contributor_details",
"=",
"None",
",",
"include_rts",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_str_param",
"(",
"params",
",",
"'user_id'",
",",
"user_id",
")",
"set_str_param",
"(",
"params",
",",
"'screen_name'",
",",
"screen_name",
")",
"set_str_param",
"(",
"params",
",",
"'since_id'",
",",
"since_id",
")",
"set_int_param",
"(",
"params",
",",
"'count'",
",",
"count",
")",
"set_str_param",
"(",
"params",
",",
"'max_id'",
",",
"max_id",
")",
"set_bool_param",
"(",
"params",
",",
"'trim_user'",
",",
"trim_user",
")",
"set_bool_param",
"(",
"params",
",",
"'exclude_replies'",
",",
"exclude_replies",
")",
"set_bool_param",
"(",
"params",
",",
"'contributor_details'",
",",
"contributor_details",
")",
"set_bool_param",
"(",
"params",
",",
"'include_rts'",
",",
"include_rts",
")",
"return",
"self",
".",
"_get_api",
"(",
"'statuses/user_timeline.json'",
",",
"params",
")"
] |
Returns a list of the most recent tweets posted by the specified user.
https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
Either ``user_id`` or ``screen_name`` must be provided.
:param str user_id:
The ID of the user to return tweets for.
:param str screen_name:
The screen name of the user to return tweets for.
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. Tweets newer than this may not be returned due to
certain API limits.
:param int count:
Specifies the number of tweets to try and retrieve, up to a maximum
of 200.
:param str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:param bool exclude_replies:
When set to ``True``, replies will not appear in the timeline.
:param bool contributor_details:
This parameter enhances the contributors element of the status
response to include the screen_name of the contributor. By default
only the user_id of the contributor is included.
:param bool include_rts:
When set to ``False``, retweets will not appear in the timeline.
:returns: A list of tweet dicts.
|
[
"Returns",
"a",
"list",
"of",
"the",
"most",
"recent",
"tweets",
"posted",
"by",
"the",
"specified",
"user",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L393-L451
|
242,540
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.statuses_home_timeline
|
def statuses_home_timeline(self, count=None, since_id=None, max_id=None,
trim_user=None, exclude_replies=None,
contributor_details=None,
include_entities=None):
"""
Returns a collection of the most recent Tweets and retweets posted by
the authenticating user and the users they follow.
https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline
:param int count:
Specifies the number of tweets to try and retrieve, up to a maximum
of 200.
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. Tweets newer than this may not be returned due to
certain API limits.
:param str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:param bool exclude_replies:
When set to ``True``, replies will not appear in the timeline.
:param bool contributor_details:
This parameter enhances the contributors element of the status
response to include the screen_name of the contributor. By default
only the user_id of the contributor is included.
:param bool include_entities:
When set to ``False``, the ``entities`` node will not be included.
:returns: A list of tweet dicts.
"""
params = {}
set_int_param(params, 'count', count)
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_bool_param(params, 'trim_user', trim_user)
set_bool_param(params, 'exclude_replies', exclude_replies)
set_bool_param(params, 'contributor_details', contributor_details)
set_bool_param(params, 'include_entities', include_entities)
return self._get_api('statuses/home_timeline.json', params)
|
python
|
def statuses_home_timeline(self, count=None, since_id=None, max_id=None,
trim_user=None, exclude_replies=None,
contributor_details=None,
include_entities=None):
"""
Returns a collection of the most recent Tweets and retweets posted by
the authenticating user and the users they follow.
https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline
:param int count:
Specifies the number of tweets to try and retrieve, up to a maximum
of 200.
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. Tweets newer than this may not be returned due to
certain API limits.
:param str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:param bool exclude_replies:
When set to ``True``, replies will not appear in the timeline.
:param bool contributor_details:
This parameter enhances the contributors element of the status
response to include the screen_name of the contributor. By default
only the user_id of the contributor is included.
:param bool include_entities:
When set to ``False``, the ``entities`` node will not be included.
:returns: A list of tweet dicts.
"""
params = {}
set_int_param(params, 'count', count)
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_bool_param(params, 'trim_user', trim_user)
set_bool_param(params, 'exclude_replies', exclude_replies)
set_bool_param(params, 'contributor_details', contributor_details)
set_bool_param(params, 'include_entities', include_entities)
return self._get_api('statuses/home_timeline.json', params)
|
[
"def",
"statuses_home_timeline",
"(",
"self",
",",
"count",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"max_id",
"=",
"None",
",",
"trim_user",
"=",
"None",
",",
"exclude_replies",
"=",
"None",
",",
"contributor_details",
"=",
"None",
",",
"include_entities",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_int_param",
"(",
"params",
",",
"'count'",
",",
"count",
")",
"set_str_param",
"(",
"params",
",",
"'since_id'",
",",
"since_id",
")",
"set_str_param",
"(",
"params",
",",
"'max_id'",
",",
"max_id",
")",
"set_bool_param",
"(",
"params",
",",
"'trim_user'",
",",
"trim_user",
")",
"set_bool_param",
"(",
"params",
",",
"'exclude_replies'",
",",
"exclude_replies",
")",
"set_bool_param",
"(",
"params",
",",
"'contributor_details'",
",",
"contributor_details",
")",
"set_bool_param",
"(",
"params",
",",
"'include_entities'",
",",
"include_entities",
")",
"return",
"self",
".",
"_get_api",
"(",
"'statuses/home_timeline.json'",
",",
"params",
")"
] |
Returns a collection of the most recent Tweets and retweets posted by
the authenticating user and the users they follow.
https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline
:param int count:
Specifies the number of tweets to try and retrieve, up to a maximum
of 200.
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. Tweets newer than this may not be returned due to
certain API limits.
:param str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:param bool exclude_replies:
When set to ``True``, replies will not appear in the timeline.
:param bool contributor_details:
This parameter enhances the contributors element of the status
response to include the screen_name of the contributor. By default
only the user_id of the contributor is included.
:param bool include_entities:
When set to ``False``, the ``entities`` node will not be included.
:returns: A list of tweet dicts.
|
[
"Returns",
"a",
"collection",
"of",
"the",
"most",
"recent",
"Tweets",
"and",
"retweets",
"posted",
"by",
"the",
"authenticating",
"user",
"and",
"the",
"users",
"they",
"follow",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L453-L501
|
242,541
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.statuses_retweets
|
def statuses_retweets(self, id, count=None, trim_user=None):
"""
Returns a list of the most recent retweets of the Tweet specified by
the id parameter.
https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param int count:
The maximum number of retweets to return. (Max 100)
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:returns: A tweet dict.
"""
params = {'id': id}
set_int_param(params, 'count', count)
set_bool_param(params, 'trim_user', trim_user)
return self._get_api('statuses/retweets.json', params)
|
python
|
def statuses_retweets(self, id, count=None, trim_user=None):
"""
Returns a list of the most recent retweets of the Tweet specified by
the id parameter.
https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param int count:
The maximum number of retweets to return. (Max 100)
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:returns: A tweet dict.
"""
params = {'id': id}
set_int_param(params, 'count', count)
set_bool_param(params, 'trim_user', trim_user)
return self._get_api('statuses/retweets.json', params)
|
[
"def",
"statuses_retweets",
"(",
"self",
",",
"id",
",",
"count",
"=",
"None",
",",
"trim_user",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'id'",
":",
"id",
"}",
"set_int_param",
"(",
"params",
",",
"'count'",
",",
"count",
")",
"set_bool_param",
"(",
"params",
",",
"'trim_user'",
",",
"trim_user",
")",
"return",
"self",
".",
"_get_api",
"(",
"'statuses/retweets.json'",
",",
"params",
")"
] |
Returns a list of the most recent retweets of the Tweet specified by
the id parameter.
https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param int count:
The maximum number of retweets to return. (Max 100)
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:returns: A tweet dict.
|
[
"Returns",
"a",
"list",
"of",
"the",
"most",
"recent",
"retweets",
"of",
"the",
"Tweet",
"specified",
"by",
"the",
"id",
"parameter",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L507-L529
|
242,542
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.statuses_show
|
def statuses_show(self, id, trim_user=None, include_my_retweet=None,
include_entities=None):
"""
Returns a single Tweet, specified by the id parameter.
https://dev.twitter.com/docs/api/1.1/get/statuses/show/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:param bool include_my_retweet:
When set to ``True``, any Tweet returned that has been retweeted by
the authenticating user will include an additional
``current_user_retweet`` node, containing the ID of the source
status for the retweet.
:param bool include_entities:
When set to ``False``, the ``entities`` node will not be included.
:returns: A tweet dict.
"""
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
set_bool_param(params, 'include_my_retweet', include_my_retweet)
set_bool_param(params, 'include_entities', include_entities)
return self._get_api('statuses/show.json', params)
|
python
|
def statuses_show(self, id, trim_user=None, include_my_retweet=None,
include_entities=None):
"""
Returns a single Tweet, specified by the id parameter.
https://dev.twitter.com/docs/api/1.1/get/statuses/show/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:param bool include_my_retweet:
When set to ``True``, any Tweet returned that has been retweeted by
the authenticating user will include an additional
``current_user_retweet`` node, containing the ID of the source
status for the retweet.
:param bool include_entities:
When set to ``False``, the ``entities`` node will not be included.
:returns: A tweet dict.
"""
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
set_bool_param(params, 'include_my_retweet', include_my_retweet)
set_bool_param(params, 'include_entities', include_entities)
return self._get_api('statuses/show.json', params)
|
[
"def",
"statuses_show",
"(",
"self",
",",
"id",
",",
"trim_user",
"=",
"None",
",",
"include_my_retweet",
"=",
"None",
",",
"include_entities",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'id'",
":",
"id",
"}",
"set_bool_param",
"(",
"params",
",",
"'trim_user'",
",",
"trim_user",
")",
"set_bool_param",
"(",
"params",
",",
"'include_my_retweet'",
",",
"include_my_retweet",
")",
"set_bool_param",
"(",
"params",
",",
"'include_entities'",
",",
"include_entities",
")",
"return",
"self",
".",
"_get_api",
"(",
"'statuses/show.json'",
",",
"params",
")"
] |
Returns a single Tweet, specified by the id parameter.
https://dev.twitter.com/docs/api/1.1/get/statuses/show/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param bool trim_user:
When set to ``True``, the tweet's user object includes only the
status author's numerical ID.
:param bool include_my_retweet:
When set to ``True``, any Tweet returned that has been retweeted by
the authenticating user will include an additional
``current_user_retweet`` node, containing the ID of the source
status for the retweet.
:param bool include_entities:
When set to ``False``, the ``entities`` node will not be included.
:returns: A tweet dict.
|
[
"Returns",
"a",
"single",
"Tweet",
"specified",
"by",
"the",
"id",
"parameter",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L531-L560
|
242,543
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.statuses_destroy
|
def statuses_destroy(self, id, trim_user=None):
"""
Destroys the status specified by the ID parameter.
https://dev.twitter.com/docs/api/1.1/post/statuses/destroy/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param bool trim_user:
When set to ``True``, the return value's user object includes only
the status author's numerical ID.
:returns:
A tweet dict containing the destroyed tweet.
"""
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
return self._post_api('statuses/destroy.json', params)
|
python
|
def statuses_destroy(self, id, trim_user=None):
"""
Destroys the status specified by the ID parameter.
https://dev.twitter.com/docs/api/1.1/post/statuses/destroy/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param bool trim_user:
When set to ``True``, the return value's user object includes only
the status author's numerical ID.
:returns:
A tweet dict containing the destroyed tweet.
"""
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
return self._post_api('statuses/destroy.json', params)
|
[
"def",
"statuses_destroy",
"(",
"self",
",",
"id",
",",
"trim_user",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'id'",
":",
"id",
"}",
"set_bool_param",
"(",
"params",
",",
"'trim_user'",
",",
"trim_user",
")",
"return",
"self",
".",
"_post_api",
"(",
"'statuses/destroy.json'",
",",
"params",
")"
] |
Destroys the status specified by the ID parameter.
https://dev.twitter.com/docs/api/1.1/post/statuses/destroy/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param bool trim_user:
When set to ``True``, the return value's user object includes only
the status author's numerical ID.
:returns:
A tweet dict containing the destroyed tweet.
|
[
"Destroys",
"the",
"status",
"specified",
"by",
"the",
"ID",
"parameter",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L562-L580
|
242,544
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.statuses_update
|
def statuses_update(self, status, in_reply_to_status_id=None, lat=None,
long=None, place_id=None, display_coordinates=None,
trim_user=None, media_ids=None):
"""
Posts a tweet.
https://dev.twitter.com/docs/api/1.1/post/statuses/update
:param str status:
(*required*) The text of your tweet, typically up to 140
characters. URL encode as necessary. t.co link wrapping may affect
character counts.
There are some special commands in this field to be aware of. For
instance, preceding a message with "D " or "M " and following it
with a screen name can create a direct message to that user if the
relationship allows for it.
:param str in_reply_to_status_id:
The ID of an existing status that the update is in reply to.
Note: This parameter will be ignored unless the author of the tweet
this parameter references is mentioned within the status text.
Therefore, you must include @username, where username is the author
of the referenced tweet, within ``status``.
:param float lat:
The latitude of the location this tweet refers to. This parameter
will be ignored unless it is inside the range -90.0 to +90.0 (North
is positive) inclusive. It will also be ignored if there isn't a
corresponding long parameter.
:param float long:
The longitude of the location this tweet refers to. The valid
ranges for longitude is -180.0 to +180.0 (East is positive)
inclusive. This parameter will be ignored if outside that range, if
it is not a number, if geo_enabled is disabled, or if there not a
corresponding lat parameter.
:param str place_id:
A place in the world. These IDs can be retrieved from GET
geo/reverse_geocode. (TODO: Reference method when it exists.)
:param bool display_coordinates:
Whether or not to put a pin on the exact coordinates a tweet has
been sent from.
:param bool trim_user:
When set to ``True``, the return value's user object includes only
the status author's numerical ID.
:param list media_ids:
A list of images previously uploaded to Twitter (referenced by
their ``media_id``) that are to be embedded in the tweet. Maximum
of four images.
:returns:
A tweet dict containing the posted tweet.
"""
params = {}
set_str_param(params, 'status', status)
set_str_param(params, 'in_reply_to_status_id', in_reply_to_status_id)
set_float_param(params, 'lat', lat, min=-90, max=90)
set_float_param(params, 'long', long, min=-180, max=180)
set_str_param(params, 'place_id', place_id)
set_bool_param(params, 'display_coordinates', display_coordinates)
set_bool_param(params, 'trim_user', trim_user)
set_list_param(params, 'media_ids', media_ids, max_len=4)
return self._post_api('statuses/update.json', params)
|
python
|
def statuses_update(self, status, in_reply_to_status_id=None, lat=None,
long=None, place_id=None, display_coordinates=None,
trim_user=None, media_ids=None):
"""
Posts a tweet.
https://dev.twitter.com/docs/api/1.1/post/statuses/update
:param str status:
(*required*) The text of your tweet, typically up to 140
characters. URL encode as necessary. t.co link wrapping may affect
character counts.
There are some special commands in this field to be aware of. For
instance, preceding a message with "D " or "M " and following it
with a screen name can create a direct message to that user if the
relationship allows for it.
:param str in_reply_to_status_id:
The ID of an existing status that the update is in reply to.
Note: This parameter will be ignored unless the author of the tweet
this parameter references is mentioned within the status text.
Therefore, you must include @username, where username is the author
of the referenced tweet, within ``status``.
:param float lat:
The latitude of the location this tweet refers to. This parameter
will be ignored unless it is inside the range -90.0 to +90.0 (North
is positive) inclusive. It will also be ignored if there isn't a
corresponding long parameter.
:param float long:
The longitude of the location this tweet refers to. The valid
ranges for longitude is -180.0 to +180.0 (East is positive)
inclusive. This parameter will be ignored if outside that range, if
it is not a number, if geo_enabled is disabled, or if there not a
corresponding lat parameter.
:param str place_id:
A place in the world. These IDs can be retrieved from GET
geo/reverse_geocode. (TODO: Reference method when it exists.)
:param bool display_coordinates:
Whether or not to put a pin on the exact coordinates a tweet has
been sent from.
:param bool trim_user:
When set to ``True``, the return value's user object includes only
the status author's numerical ID.
:param list media_ids:
A list of images previously uploaded to Twitter (referenced by
their ``media_id``) that are to be embedded in the tweet. Maximum
of four images.
:returns:
A tweet dict containing the posted tweet.
"""
params = {}
set_str_param(params, 'status', status)
set_str_param(params, 'in_reply_to_status_id', in_reply_to_status_id)
set_float_param(params, 'lat', lat, min=-90, max=90)
set_float_param(params, 'long', long, min=-180, max=180)
set_str_param(params, 'place_id', place_id)
set_bool_param(params, 'display_coordinates', display_coordinates)
set_bool_param(params, 'trim_user', trim_user)
set_list_param(params, 'media_ids', media_ids, max_len=4)
return self._post_api('statuses/update.json', params)
|
[
"def",
"statuses_update",
"(",
"self",
",",
"status",
",",
"in_reply_to_status_id",
"=",
"None",
",",
"lat",
"=",
"None",
",",
"long",
"=",
"None",
",",
"place_id",
"=",
"None",
",",
"display_coordinates",
"=",
"None",
",",
"trim_user",
"=",
"None",
",",
"media_ids",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_str_param",
"(",
"params",
",",
"'status'",
",",
"status",
")",
"set_str_param",
"(",
"params",
",",
"'in_reply_to_status_id'",
",",
"in_reply_to_status_id",
")",
"set_float_param",
"(",
"params",
",",
"'lat'",
",",
"lat",
",",
"min",
"=",
"-",
"90",
",",
"max",
"=",
"90",
")",
"set_float_param",
"(",
"params",
",",
"'long'",
",",
"long",
",",
"min",
"=",
"-",
"180",
",",
"max",
"=",
"180",
")",
"set_str_param",
"(",
"params",
",",
"'place_id'",
",",
"place_id",
")",
"set_bool_param",
"(",
"params",
",",
"'display_coordinates'",
",",
"display_coordinates",
")",
"set_bool_param",
"(",
"params",
",",
"'trim_user'",
",",
"trim_user",
")",
"set_list_param",
"(",
"params",
",",
"'media_ids'",
",",
"media_ids",
",",
"max_len",
"=",
"4",
")",
"return",
"self",
".",
"_post_api",
"(",
"'statuses/update.json'",
",",
"params",
")"
] |
Posts a tweet.
https://dev.twitter.com/docs/api/1.1/post/statuses/update
:param str status:
(*required*) The text of your tweet, typically up to 140
characters. URL encode as necessary. t.co link wrapping may affect
character counts.
There are some special commands in this field to be aware of. For
instance, preceding a message with "D " or "M " and following it
with a screen name can create a direct message to that user if the
relationship allows for it.
:param str in_reply_to_status_id:
The ID of an existing status that the update is in reply to.
Note: This parameter will be ignored unless the author of the tweet
this parameter references is mentioned within the status text.
Therefore, you must include @username, where username is the author
of the referenced tweet, within ``status``.
:param float lat:
The latitude of the location this tweet refers to. This parameter
will be ignored unless it is inside the range -90.0 to +90.0 (North
is positive) inclusive. It will also be ignored if there isn't a
corresponding long parameter.
:param float long:
The longitude of the location this tweet refers to. The valid
ranges for longitude is -180.0 to +180.0 (East is positive)
inclusive. This parameter will be ignored if outside that range, if
it is not a number, if geo_enabled is disabled, or if there not a
corresponding lat parameter.
:param str place_id:
A place in the world. These IDs can be retrieved from GET
geo/reverse_geocode. (TODO: Reference method when it exists.)
:param bool display_coordinates:
Whether or not to put a pin on the exact coordinates a tweet has
been sent from.
:param bool trim_user:
When set to ``True``, the return value's user object includes only
the status author's numerical ID.
:param list media_ids:
A list of images previously uploaded to Twitter (referenced by
their ``media_id``) that are to be embedded in the tweet. Maximum
of four images.
:returns:
A tweet dict containing the posted tweet.
|
[
"Posts",
"a",
"tweet",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L582-L650
|
242,545
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.statuses_retweet
|
def statuses_retweet(self, id, trim_user=None):
"""
Retweets the status specified by the ID parameter.
https://dev.twitter.com/docs/api/1.1/post/statuses/retweet/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param bool trim_user:
When set to ``True``, the return value's user object includes only
the status author's numerical ID.
:returns:
A tweet dict containing the retweet. (Contains the retweeted tweet
in the ``retweeted_status`` field.)
"""
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
return self._post_api('statuses/retweet.json', params)
|
python
|
def statuses_retweet(self, id, trim_user=None):
"""
Retweets the status specified by the ID parameter.
https://dev.twitter.com/docs/api/1.1/post/statuses/retweet/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param bool trim_user:
When set to ``True``, the return value's user object includes only
the status author's numerical ID.
:returns:
A tweet dict containing the retweet. (Contains the retweeted tweet
in the ``retweeted_status`` field.)
"""
params = {'id': id}
set_bool_param(params, 'trim_user', trim_user)
return self._post_api('statuses/retweet.json', params)
|
[
"def",
"statuses_retweet",
"(",
"self",
",",
"id",
",",
"trim_user",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'id'",
":",
"id",
"}",
"set_bool_param",
"(",
"params",
",",
"'trim_user'",
",",
"trim_user",
")",
"return",
"self",
".",
"_post_api",
"(",
"'statuses/retweet.json'",
",",
"params",
")"
] |
Retweets the status specified by the ID parameter.
https://dev.twitter.com/docs/api/1.1/post/statuses/retweet/%3Aid
:param str id:
(*required*) The numerical ID of the desired tweet.
:param bool trim_user:
When set to ``True``, the return value's user object includes only
the status author's numerical ID.
:returns:
A tweet dict containing the retweet. (Contains the retweeted tweet
in the ``retweeted_status`` field.)
|
[
"Retweets",
"the",
"status",
"specified",
"by",
"the",
"ID",
"parameter",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L652-L671
|
242,546
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.media_upload
|
def media_upload(self, media, additional_owners=None):
"""
Uploads an image to Twitter for later embedding in tweets.
https://dev.twitter.com/rest/reference/post/media/upload
:param file media:
The image file to upload (see the API docs for limitations).
:param list additional_owners:
A list of Twitter users that will be able to access the uploaded
file and embed it in their tweets (maximum 100 users).
:returns:
A dict containing information about the file uploaded. (Contains
the media id needed to embed the image in the ``media_id`` field).
"""
params = {}
set_list_param(
params, 'additional_owners', additional_owners, max_len=100)
return self._upload_media('media/upload.json', media, params)
|
python
|
def media_upload(self, media, additional_owners=None):
"""
Uploads an image to Twitter for later embedding in tweets.
https://dev.twitter.com/rest/reference/post/media/upload
:param file media:
The image file to upload (see the API docs for limitations).
:param list additional_owners:
A list of Twitter users that will be able to access the uploaded
file and embed it in their tweets (maximum 100 users).
:returns:
A dict containing information about the file uploaded. (Contains
the media id needed to embed the image in the ``media_id`` field).
"""
params = {}
set_list_param(
params, 'additional_owners', additional_owners, max_len=100)
return self._upload_media('media/upload.json', media, params)
|
[
"def",
"media_upload",
"(",
"self",
",",
"media",
",",
"additional_owners",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_list_param",
"(",
"params",
",",
"'additional_owners'",
",",
"additional_owners",
",",
"max_len",
"=",
"100",
")",
"return",
"self",
".",
"_upload_media",
"(",
"'media/upload.json'",
",",
"media",
",",
"params",
")"
] |
Uploads an image to Twitter for later embedding in tweets.
https://dev.twitter.com/rest/reference/post/media/upload
:param file media:
The image file to upload (see the API docs for limitations).
:param list additional_owners:
A list of Twitter users that will be able to access the uploaded
file and embed it in their tweets (maximum 100 users).
:returns:
A dict containing information about the file uploaded. (Contains
the media id needed to embed the image in the ``media_id`` field).
|
[
"Uploads",
"an",
"image",
"to",
"Twitter",
"for",
"later",
"embedding",
"in",
"tweets",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L673-L693
|
242,547
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.stream_filter
|
def stream_filter(self, delegate, follow=None, track=None, locations=None,
stall_warnings=None):
"""
Streams public messages filtered by various parameters.
https://dev.twitter.com/docs/api/1.1/post/statuses/filter
At least one of ``follow``, ``track``, or ``locations`` must be
provided. See the API documentation linked above for details on these
parameters and the various limits on this API.
:param delegate:
A delegate function that will be called for each message in the
stream and will be passed the message dict as the only parameter.
The message dicts passed to this function may represent any message
type and the delegate is responsible for any dispatch that may be
required. (:mod:`txtwitter.messagetools` may be helpful here.)
:param list follow:
A list of user IDs, indicating the users to return statuses for in
the stream.
:param list track:
List of keywords to track.
:param list locations:
List of location bounding boxes to track.
XXX: Currently unsupported.
:param bool stall_warnings:
Specifies whether stall warnings should be delivered.
:returns: An unstarted :class:`TwitterStreamService`.
"""
params = {}
if follow is not None:
params['follow'] = ','.join(follow)
if track is not None:
params['track'] = ','.join(track)
if locations is not None:
raise NotImplementedError(
"The `locations` parameter is not yet supported.")
set_bool_param(params, 'stall_warnings', stall_warnings)
svc = TwitterStreamService(
lambda: self._post_stream('statuses/filter.json', params),
delegate)
return svc
|
python
|
def stream_filter(self, delegate, follow=None, track=None, locations=None,
stall_warnings=None):
"""
Streams public messages filtered by various parameters.
https://dev.twitter.com/docs/api/1.1/post/statuses/filter
At least one of ``follow``, ``track``, or ``locations`` must be
provided. See the API documentation linked above for details on these
parameters and the various limits on this API.
:param delegate:
A delegate function that will be called for each message in the
stream and will be passed the message dict as the only parameter.
The message dicts passed to this function may represent any message
type and the delegate is responsible for any dispatch that may be
required. (:mod:`txtwitter.messagetools` may be helpful here.)
:param list follow:
A list of user IDs, indicating the users to return statuses for in
the stream.
:param list track:
List of keywords to track.
:param list locations:
List of location bounding boxes to track.
XXX: Currently unsupported.
:param bool stall_warnings:
Specifies whether stall warnings should be delivered.
:returns: An unstarted :class:`TwitterStreamService`.
"""
params = {}
if follow is not None:
params['follow'] = ','.join(follow)
if track is not None:
params['track'] = ','.join(track)
if locations is not None:
raise NotImplementedError(
"The `locations` parameter is not yet supported.")
set_bool_param(params, 'stall_warnings', stall_warnings)
svc = TwitterStreamService(
lambda: self._post_stream('statuses/filter.json', params),
delegate)
return svc
|
[
"def",
"stream_filter",
"(",
"self",
",",
"delegate",
",",
"follow",
"=",
"None",
",",
"track",
"=",
"None",
",",
"locations",
"=",
"None",
",",
"stall_warnings",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"follow",
"is",
"not",
"None",
":",
"params",
"[",
"'follow'",
"]",
"=",
"','",
".",
"join",
"(",
"follow",
")",
"if",
"track",
"is",
"not",
"None",
":",
"params",
"[",
"'track'",
"]",
"=",
"','",
".",
"join",
"(",
"track",
")",
"if",
"locations",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"The `locations` parameter is not yet supported.\"",
")",
"set_bool_param",
"(",
"params",
",",
"'stall_warnings'",
",",
"stall_warnings",
")",
"svc",
"=",
"TwitterStreamService",
"(",
"lambda",
":",
"self",
".",
"_post_stream",
"(",
"'statuses/filter.json'",
",",
"params",
")",
",",
"delegate",
")",
"return",
"svc"
] |
Streams public messages filtered by various parameters.
https://dev.twitter.com/docs/api/1.1/post/statuses/filter
At least one of ``follow``, ``track``, or ``locations`` must be
provided. See the API documentation linked above for details on these
parameters and the various limits on this API.
:param delegate:
A delegate function that will be called for each message in the
stream and will be passed the message dict as the only parameter.
The message dicts passed to this function may represent any message
type and the delegate is responsible for any dispatch that may be
required. (:mod:`txtwitter.messagetools` may be helpful here.)
:param list follow:
A list of user IDs, indicating the users to return statuses for in
the stream.
:param list track:
List of keywords to track.
:param list locations:
List of location bounding boxes to track.
XXX: Currently unsupported.
:param bool stall_warnings:
Specifies whether stall warnings should be delivered.
:returns: An unstarted :class:`TwitterStreamService`.
|
[
"Streams",
"public",
"messages",
"filtered",
"by",
"various",
"parameters",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L705-L752
|
242,548
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.userstream_user
|
def userstream_user(self, delegate, stall_warnings=None,
with_='followings', replies=None):
"""
Streams messages for a single user.
https://dev.twitter.com/docs/api/1.1/get/user
The ``stringify_friend_ids`` parameter is always set to ``'true'`` for
consistency with the use of string identifiers elsewhere.
:param delegate:
A delegate function that will be called for each message in the
stream and will be passed the message dict as the only parameter.
The message dicts passed to this function may represent any message
type and the delegate is responsible for any dispatch that may be
required. (:mod:`txtwitter.messagetools` may be helpful here.)
:param bool stall_warnings:
Specifies whether stall warnings should be delivered.
:param str with_:
If ``'followings'`` (the default), the stream will include messages
from both the authenticated user and the authenticated user's
followers. If ``'user'``, the stream will only include messages
from (or mentioning) the autheticated user. All other values are
invalid. (The underscore appended to the parameter name is to avoid
conflicting with Python's ``with`` keyword.)
:param str replies:
If set to ``'all'``, replies to tweets will be included even if the
authenticated user does not follow both parties.
:returns: An unstarted :class:`TwitterStreamService`.
"""
params = {'stringify_friend_ids': 'true'}
set_bool_param(params, 'stall_warnings', stall_warnings)
set_str_param(params, 'with', with_)
set_str_param(params, 'replies', replies)
svc = TwitterStreamService(
lambda: self._get_userstream('user.json', params),
delegate)
return svc
|
python
|
def userstream_user(self, delegate, stall_warnings=None,
with_='followings', replies=None):
"""
Streams messages for a single user.
https://dev.twitter.com/docs/api/1.1/get/user
The ``stringify_friend_ids`` parameter is always set to ``'true'`` for
consistency with the use of string identifiers elsewhere.
:param delegate:
A delegate function that will be called for each message in the
stream and will be passed the message dict as the only parameter.
The message dicts passed to this function may represent any message
type and the delegate is responsible for any dispatch that may be
required. (:mod:`txtwitter.messagetools` may be helpful here.)
:param bool stall_warnings:
Specifies whether stall warnings should be delivered.
:param str with_:
If ``'followings'`` (the default), the stream will include messages
from both the authenticated user and the authenticated user's
followers. If ``'user'``, the stream will only include messages
from (or mentioning) the autheticated user. All other values are
invalid. (The underscore appended to the parameter name is to avoid
conflicting with Python's ``with`` keyword.)
:param str replies:
If set to ``'all'``, replies to tweets will be included even if the
authenticated user does not follow both parties.
:returns: An unstarted :class:`TwitterStreamService`.
"""
params = {'stringify_friend_ids': 'true'}
set_bool_param(params, 'stall_warnings', stall_warnings)
set_str_param(params, 'with', with_)
set_str_param(params, 'replies', replies)
svc = TwitterStreamService(
lambda: self._get_userstream('user.json', params),
delegate)
return svc
|
[
"def",
"userstream_user",
"(",
"self",
",",
"delegate",
",",
"stall_warnings",
"=",
"None",
",",
"with_",
"=",
"'followings'",
",",
"replies",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'stringify_friend_ids'",
":",
"'true'",
"}",
"set_bool_param",
"(",
"params",
",",
"'stall_warnings'",
",",
"stall_warnings",
")",
"set_str_param",
"(",
"params",
",",
"'with'",
",",
"with_",
")",
"set_str_param",
"(",
"params",
",",
"'replies'",
",",
"replies",
")",
"svc",
"=",
"TwitterStreamService",
"(",
"lambda",
":",
"self",
".",
"_get_userstream",
"(",
"'user.json'",
",",
"params",
")",
",",
"delegate",
")",
"return",
"svc"
] |
Streams messages for a single user.
https://dev.twitter.com/docs/api/1.1/get/user
The ``stringify_friend_ids`` parameter is always set to ``'true'`` for
consistency with the use of string identifiers elsewhere.
:param delegate:
A delegate function that will be called for each message in the
stream and will be passed the message dict as the only parameter.
The message dicts passed to this function may represent any message
type and the delegate is responsible for any dispatch that may be
required. (:mod:`txtwitter.messagetools` may be helpful here.)
:param bool stall_warnings:
Specifies whether stall warnings should be delivered.
:param str with_:
If ``'followings'`` (the default), the stream will include messages
from both the authenticated user and the authenticated user's
followers. If ``'user'``, the stream will only include messages
from (or mentioning) the autheticated user. All other values are
invalid. (The underscore appended to the parameter name is to avoid
conflicting with Python's ``with`` keyword.)
:param str replies:
If set to ``'all'``, replies to tweets will be included even if the
authenticated user does not follow both parties.
:returns: An unstarted :class:`TwitterStreamService`.
|
[
"Streams",
"messages",
"for",
"a",
"single",
"user",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L757-L799
|
242,549
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.direct_messages
|
def direct_messages(self, since_id=None, max_id=None, count=None,
include_entities=None, skip_status=None):
"""
Gets the 20 most recent direct messages received by the authenticating
user.
https://dev.twitter.com/docs/api/1.1/get/direct_messages
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. There are limits to the number of Tweets which
can be accessed through the API. If the limit of Tweets has occured
since the since_id, the since_id will be forced to the oldest ID
available.
:params str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param int count:
Specifies the number of direct messages to try and retrieve, up to
a maximum of ``200``. The value of count is best thought of as a
limit to the number of Tweets to return because suspended or
deleted content is removed after the count has been applied.
:param bool include_entities:
The entities node will not be included when set to ``False``.
:param bool skip_status:
When set to ``True``, statuses will not be included in the returned
user objects.
:returns:
A list of direct message dicts.
"""
params = {}
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_int_param(params, 'count', count)
set_bool_param(params, 'include_entities', include_entities)
set_bool_param(params, 'skip_status', skip_status)
return self._get_api('direct_messages.json', params)
|
python
|
def direct_messages(self, since_id=None, max_id=None, count=None,
include_entities=None, skip_status=None):
"""
Gets the 20 most recent direct messages received by the authenticating
user.
https://dev.twitter.com/docs/api/1.1/get/direct_messages
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. There are limits to the number of Tweets which
can be accessed through the API. If the limit of Tweets has occured
since the since_id, the since_id will be forced to the oldest ID
available.
:params str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param int count:
Specifies the number of direct messages to try and retrieve, up to
a maximum of ``200``. The value of count is best thought of as a
limit to the number of Tweets to return because suspended or
deleted content is removed after the count has been applied.
:param bool include_entities:
The entities node will not be included when set to ``False``.
:param bool skip_status:
When set to ``True``, statuses will not be included in the returned
user objects.
:returns:
A list of direct message dicts.
"""
params = {}
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_int_param(params, 'count', count)
set_bool_param(params, 'include_entities', include_entities)
set_bool_param(params, 'skip_status', skip_status)
return self._get_api('direct_messages.json', params)
|
[
"def",
"direct_messages",
"(",
"self",
",",
"since_id",
"=",
"None",
",",
"max_id",
"=",
"None",
",",
"count",
"=",
"None",
",",
"include_entities",
"=",
"None",
",",
"skip_status",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_str_param",
"(",
"params",
",",
"'since_id'",
",",
"since_id",
")",
"set_str_param",
"(",
"params",
",",
"'max_id'",
",",
"max_id",
")",
"set_int_param",
"(",
"params",
",",
"'count'",
",",
"count",
")",
"set_bool_param",
"(",
"params",
",",
"'include_entities'",
",",
"include_entities",
")",
"set_bool_param",
"(",
"params",
",",
"'skip_status'",
",",
"skip_status",
")",
"return",
"self",
".",
"_get_api",
"(",
"'direct_messages.json'",
",",
"params",
")"
] |
Gets the 20 most recent direct messages received by the authenticating
user.
https://dev.twitter.com/docs/api/1.1/get/direct_messages
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. There are limits to the number of Tweets which
can be accessed through the API. If the limit of Tweets has occured
since the since_id, the since_id will be forced to the oldest ID
available.
:params str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param int count:
Specifies the number of direct messages to try and retrieve, up to
a maximum of ``200``. The value of count is best thought of as a
limit to the number of Tweets to return because suspended or
deleted content is removed after the count has been applied.
:param bool include_entities:
The entities node will not be included when set to ``False``.
:param bool skip_status:
When set to ``True``, statuses will not be included in the returned
user objects.
:returns:
A list of direct message dicts.
|
[
"Gets",
"the",
"20",
"most",
"recent",
"direct",
"messages",
"received",
"by",
"the",
"authenticating",
"user",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L803-L844
|
242,550
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.direct_messages_sent
|
def direct_messages_sent(self, since_id=None, max_id=None, count=None,
include_entities=None, page=None):
"""
Gets the 20 most recent direct messages sent by the authenticating
user.
https://dev.twitter.com/docs/api/1.1/get/direct_messages/sent
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. There are limits to the number of Tweets which
can be accessed through the API. If the limit of Tweets has occured
since the since_id, the since_id will be forced to the oldest ID
available.
:params str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param int count:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param int page:
Specifies the page of results to retrieve.
:param bool include_entities:
The entities node will not be included when set to ``False``.
:returns:
A list of direct message dicts.
"""
params = {}
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_int_param(params, 'count', count)
set_int_param(params, 'page', page)
set_bool_param(params, 'include_entities', include_entities)
return self._get_api('direct_messages/sent.json', params)
|
python
|
def direct_messages_sent(self, since_id=None, max_id=None, count=None,
include_entities=None, page=None):
"""
Gets the 20 most recent direct messages sent by the authenticating
user.
https://dev.twitter.com/docs/api/1.1/get/direct_messages/sent
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. There are limits to the number of Tweets which
can be accessed through the API. If the limit of Tweets has occured
since the since_id, the since_id will be forced to the oldest ID
available.
:params str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param int count:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param int page:
Specifies the page of results to retrieve.
:param bool include_entities:
The entities node will not be included when set to ``False``.
:returns:
A list of direct message dicts.
"""
params = {}
set_str_param(params, 'since_id', since_id)
set_str_param(params, 'max_id', max_id)
set_int_param(params, 'count', count)
set_int_param(params, 'page', page)
set_bool_param(params, 'include_entities', include_entities)
return self._get_api('direct_messages/sent.json', params)
|
[
"def",
"direct_messages_sent",
"(",
"self",
",",
"since_id",
"=",
"None",
",",
"max_id",
"=",
"None",
",",
"count",
"=",
"None",
",",
"include_entities",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_str_param",
"(",
"params",
",",
"'since_id'",
",",
"since_id",
")",
"set_str_param",
"(",
"params",
",",
"'max_id'",
",",
"max_id",
")",
"set_int_param",
"(",
"params",
",",
"'count'",
",",
"count",
")",
"set_int_param",
"(",
"params",
",",
"'page'",
",",
"page",
")",
"set_bool_param",
"(",
"params",
",",
"'include_entities'",
",",
"include_entities",
")",
"return",
"self",
".",
"_get_api",
"(",
"'direct_messages/sent.json'",
",",
"params",
")"
] |
Gets the 20 most recent direct messages sent by the authenticating
user.
https://dev.twitter.com/docs/api/1.1/get/direct_messages/sent
:param str since_id:
Returns results with an ID greater than (that is, more recent than)
the specified ID. There are limits to the number of Tweets which
can be accessed through the API. If the limit of Tweets has occured
since the since_id, the since_id will be forced to the oldest ID
available.
:params str max_id:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param int count:
Returns results with an ID less than (that is, older than) or equal
to the specified ID.
:param int page:
Specifies the page of results to retrieve.
:param bool include_entities:
The entities node will not be included when set to ``False``.
:returns:
A list of direct message dicts.
|
[
"Gets",
"the",
"20",
"most",
"recent",
"direct",
"messages",
"sent",
"by",
"the",
"authenticating",
"user",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L846-L884
|
242,551
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.direct_messages_show
|
def direct_messages_show(self, id):
"""
Gets the direct message with the given id.
https://dev.twitter.com/docs/api/1.1/get/direct_messages/show
:param str id:
(*required*) The ID of the direct message.
:returns:
A direct message dict.
"""
params = {}
set_str_param(params, 'id', id)
d = self._get_api('direct_messages/show.json', params)
d.addCallback(lambda dms: dms[0])
return d
|
python
|
def direct_messages_show(self, id):
"""
Gets the direct message with the given id.
https://dev.twitter.com/docs/api/1.1/get/direct_messages/show
:param str id:
(*required*) The ID of the direct message.
:returns:
A direct message dict.
"""
params = {}
set_str_param(params, 'id', id)
d = self._get_api('direct_messages/show.json', params)
d.addCallback(lambda dms: dms[0])
return d
|
[
"def",
"direct_messages_show",
"(",
"self",
",",
"id",
")",
":",
"params",
"=",
"{",
"}",
"set_str_param",
"(",
"params",
",",
"'id'",
",",
"id",
")",
"d",
"=",
"self",
".",
"_get_api",
"(",
"'direct_messages/show.json'",
",",
"params",
")",
"d",
".",
"addCallback",
"(",
"lambda",
"dms",
":",
"dms",
"[",
"0",
"]",
")",
"return",
"d"
] |
Gets the direct message with the given id.
https://dev.twitter.com/docs/api/1.1/get/direct_messages/show
:param str id:
(*required*) The ID of the direct message.
:returns:
A direct message dict.
|
[
"Gets",
"the",
"direct",
"message",
"with",
"the",
"given",
"id",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L886-L902
|
242,552
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.direct_messages_destroy
|
def direct_messages_destroy(self, id, include_entities=None):
"""
Destroys the direct message with the given id.
https://dev.twitter.com/docs/api/1.1/post/direct_messages/destroy
:param str id:
(*required*) The ID of the direct message.
:param bool include_entities:
The entities node will not be included when set to ``False``.
:returns:
A direct message dict containing the destroyed direct message.
"""
params = {}
set_str_param(params, 'id', id)
set_bool_param(params, 'include_entities', include_entities)
return self._post_api('direct_messages/destroy.json', params)
|
python
|
def direct_messages_destroy(self, id, include_entities=None):
"""
Destroys the direct message with the given id.
https://dev.twitter.com/docs/api/1.1/post/direct_messages/destroy
:param str id:
(*required*) The ID of the direct message.
:param bool include_entities:
The entities node will not be included when set to ``False``.
:returns:
A direct message dict containing the destroyed direct message.
"""
params = {}
set_str_param(params, 'id', id)
set_bool_param(params, 'include_entities', include_entities)
return self._post_api('direct_messages/destroy.json', params)
|
[
"def",
"direct_messages_destroy",
"(",
"self",
",",
"id",
",",
"include_entities",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_str_param",
"(",
"params",
",",
"'id'",
",",
"id",
")",
"set_bool_param",
"(",
"params",
",",
"'include_entities'",
",",
"include_entities",
")",
"return",
"self",
".",
"_post_api",
"(",
"'direct_messages/destroy.json'",
",",
"params",
")"
] |
Destroys the direct message with the given id.
https://dev.twitter.com/docs/api/1.1/post/direct_messages/destroy
:param str id:
(*required*) The ID of the direct message.
:param bool include_entities:
The entities node will not be included when set to ``False``.
:returns:
A direct message dict containing the destroyed direct message.
|
[
"Destroys",
"the",
"direct",
"message",
"with",
"the",
"given",
"id",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L904-L921
|
242,553
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.direct_messages_new
|
def direct_messages_new(self, text, user_id=None, screen_name=None):
"""
Sends a new direct message to the given user from the authenticating
user.
https://dev.twitter.com/docs/api/1.1/post/direct_messages/new
:param str text:
(*required*) The text of your direct message.
:param str user_id:
The ID of the user who should receive the direct message. Required
if ``screen_name`` isn't given.
:param str screen_name:
The screen name of the user who should receive the direct message.
Required if ``user_id`` isn't given.
:returns:
A direct message dict containing the sent direct message.
"""
params = {}
set_str_param(params, 'text', text)
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
return self._post_api('direct_messages/new.json', params)
|
python
|
def direct_messages_new(self, text, user_id=None, screen_name=None):
"""
Sends a new direct message to the given user from the authenticating
user.
https://dev.twitter.com/docs/api/1.1/post/direct_messages/new
:param str text:
(*required*) The text of your direct message.
:param str user_id:
The ID of the user who should receive the direct message. Required
if ``screen_name`` isn't given.
:param str screen_name:
The screen name of the user who should receive the direct message.
Required if ``user_id`` isn't given.
:returns:
A direct message dict containing the sent direct message.
"""
params = {}
set_str_param(params, 'text', text)
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
return self._post_api('direct_messages/new.json', params)
|
[
"def",
"direct_messages_new",
"(",
"self",
",",
"text",
",",
"user_id",
"=",
"None",
",",
"screen_name",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_str_param",
"(",
"params",
",",
"'text'",
",",
"text",
")",
"set_str_param",
"(",
"params",
",",
"'user_id'",
",",
"user_id",
")",
"set_str_param",
"(",
"params",
",",
"'screen_name'",
",",
"screen_name",
")",
"return",
"self",
".",
"_post_api",
"(",
"'direct_messages/new.json'",
",",
"params",
")"
] |
Sends a new direct message to the given user from the authenticating
user.
https://dev.twitter.com/docs/api/1.1/post/direct_messages/new
:param str text:
(*required*) The text of your direct message.
:param str user_id:
The ID of the user who should receive the direct message. Required
if ``screen_name`` isn't given.
:param str screen_name:
The screen name of the user who should receive the direct message.
Required if ``user_id`` isn't given.
:returns:
A direct message dict containing the sent direct message.
|
[
"Sends",
"a",
"new",
"direct",
"message",
"to",
"the",
"given",
"user",
"from",
"the",
"authenticating",
"user",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L923-L946
|
242,554
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.friendships_create
|
def friendships_create(self, user_id=None, screen_name=None,
follow=None):
"""
Allows the authenticating users to follow the specified user.
https://dev.twitter.com/docs/api/1.1/post/friendships/create
:param str user_id:
The screen name of the user for whom to befriend. Required if
``screen_name`` isn't given.
:param str screen_name:
The ID of the user for whom to befriend. Required if ``user_id``
isn't given.
:param bool follow:
Enable notifications for the target user.
:returns:
A dict containing the newly followed user.
"""
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
set_bool_param(params, 'follow', follow)
return self._post_api('friendships/create.json', params)
|
python
|
def friendships_create(self, user_id=None, screen_name=None,
follow=None):
"""
Allows the authenticating users to follow the specified user.
https://dev.twitter.com/docs/api/1.1/post/friendships/create
:param str user_id:
The screen name of the user for whom to befriend. Required if
``screen_name`` isn't given.
:param str screen_name:
The ID of the user for whom to befriend. Required if ``user_id``
isn't given.
:param bool follow:
Enable notifications for the target user.
:returns:
A dict containing the newly followed user.
"""
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
set_bool_param(params, 'follow', follow)
return self._post_api('friendships/create.json', params)
|
[
"def",
"friendships_create",
"(",
"self",
",",
"user_id",
"=",
"None",
",",
"screen_name",
"=",
"None",
",",
"follow",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_str_param",
"(",
"params",
",",
"'user_id'",
",",
"user_id",
")",
"set_str_param",
"(",
"params",
",",
"'screen_name'",
",",
"screen_name",
")",
"set_bool_param",
"(",
"params",
",",
"'follow'",
",",
"follow",
")",
"return",
"self",
".",
"_post_api",
"(",
"'friendships/create.json'",
",",
"params",
")"
] |
Allows the authenticating users to follow the specified user.
https://dev.twitter.com/docs/api/1.1/post/friendships/create
:param str user_id:
The screen name of the user for whom to befriend. Required if
``screen_name`` isn't given.
:param str screen_name:
The ID of the user for whom to befriend. Required if ``user_id``
isn't given.
:param bool follow:
Enable notifications for the target user.
:returns:
A dict containing the newly followed user.
|
[
"Allows",
"the",
"authenticating",
"users",
"to",
"follow",
"the",
"specified",
"user",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L961-L984
|
242,555
|
jerith/txTwitter
|
txtwitter/twitter.py
|
TwitterClient.friendships_destroy
|
def friendships_destroy(self, user_id=None, screen_name=None):
"""
Allows the authenticating user to unfollow the specified user.
https://dev.twitter.com/docs/api/1.1/post/friendships/destroy
:param str user_id:
The screen name of the user for whom to unfollow. Required if
``screen_name`` isn't given.
:param str screen_name:
The ID of the user for whom to unfollow. Required if ``user_id``
isn't given.
:returns:
A dict containing the newly unfollowed user.
"""
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
return self._post_api('friendships/destroy.json', params)
|
python
|
def friendships_destroy(self, user_id=None, screen_name=None):
"""
Allows the authenticating user to unfollow the specified user.
https://dev.twitter.com/docs/api/1.1/post/friendships/destroy
:param str user_id:
The screen name of the user for whom to unfollow. Required if
``screen_name`` isn't given.
:param str screen_name:
The ID of the user for whom to unfollow. Required if ``user_id``
isn't given.
:returns:
A dict containing the newly unfollowed user.
"""
params = {}
set_str_param(params, 'user_id', user_id)
set_str_param(params, 'screen_name', screen_name)
return self._post_api('friendships/destroy.json', params)
|
[
"def",
"friendships_destroy",
"(",
"self",
",",
"user_id",
"=",
"None",
",",
"screen_name",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"set_str_param",
"(",
"params",
",",
"'user_id'",
",",
"user_id",
")",
"set_str_param",
"(",
"params",
",",
"'screen_name'",
",",
"screen_name",
")",
"return",
"self",
".",
"_post_api",
"(",
"'friendships/destroy.json'",
",",
"params",
")"
] |
Allows the authenticating user to unfollow the specified user.
https://dev.twitter.com/docs/api/1.1/post/friendships/destroy
:param str user_id:
The screen name of the user for whom to unfollow. Required if
``screen_name`` isn't given.
:param str screen_name:
The ID of the user for whom to unfollow. Required if ``user_id``
isn't given.
:returns:
A dict containing the newly unfollowed user.
|
[
"Allows",
"the",
"authenticating",
"user",
"to",
"unfollow",
"the",
"specified",
"user",
"."
] |
f07afd21184cd1bee697737bf98fd143378dbdff
|
https://github.com/jerith/txTwitter/blob/f07afd21184cd1bee697737bf98fd143378dbdff/txtwitter/twitter.py#L986-L1005
|
242,556
|
pwyliu/clancy
|
clancy/redoctober.py
|
api_call
|
def api_call(endpoint, args, payload):
"""
Generic function to call the RO API
"""
headers = {'content-type': 'application/json; ; charset=utf-8'}
url = 'https://{}/{}'.format(args['--server'], endpoint)
attempt = 0
resp = None
while True:
try:
attempt += 1
resp = requests.post(
url, data=json.dumps(payload), headers=headers,
verify=args['--cacert']
)
resp.raise_for_status()
break
except (socket_timeout, requests.Timeout,
requests.ConnectionError, requests.URLRequired) as ex:
abort('{}'.format(ex))
except requests.HTTPError as ex:
warn('Requests HTTP error: {}'.format(ex))
if attempt >= 5:
abort('Too many HTTP errors.')
if resp is not None:
try:
return resp.json()
except ValueError:
abort('Unexpected response from server:\n\n{}'.format(resp.text))
else:
abort("Couldn't POST to Red October")
|
python
|
def api_call(endpoint, args, payload):
"""
Generic function to call the RO API
"""
headers = {'content-type': 'application/json; ; charset=utf-8'}
url = 'https://{}/{}'.format(args['--server'], endpoint)
attempt = 0
resp = None
while True:
try:
attempt += 1
resp = requests.post(
url, data=json.dumps(payload), headers=headers,
verify=args['--cacert']
)
resp.raise_for_status()
break
except (socket_timeout, requests.Timeout,
requests.ConnectionError, requests.URLRequired) as ex:
abort('{}'.format(ex))
except requests.HTTPError as ex:
warn('Requests HTTP error: {}'.format(ex))
if attempt >= 5:
abort('Too many HTTP errors.')
if resp is not None:
try:
return resp.json()
except ValueError:
abort('Unexpected response from server:\n\n{}'.format(resp.text))
else:
abort("Couldn't POST to Red October")
|
[
"def",
"api_call",
"(",
"endpoint",
",",
"args",
",",
"payload",
")",
":",
"headers",
"=",
"{",
"'content-type'",
":",
"'application/json; ; charset=utf-8'",
"}",
"url",
"=",
"'https://{}/{}'",
".",
"format",
"(",
"args",
"[",
"'--server'",
"]",
",",
"endpoint",
")",
"attempt",
"=",
"0",
"resp",
"=",
"None",
"while",
"True",
":",
"try",
":",
"attempt",
"+=",
"1",
"resp",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
",",
"headers",
"=",
"headers",
",",
"verify",
"=",
"args",
"[",
"'--cacert'",
"]",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"break",
"except",
"(",
"socket_timeout",
",",
"requests",
".",
"Timeout",
",",
"requests",
".",
"ConnectionError",
",",
"requests",
".",
"URLRequired",
")",
"as",
"ex",
":",
"abort",
"(",
"'{}'",
".",
"format",
"(",
"ex",
")",
")",
"except",
"requests",
".",
"HTTPError",
"as",
"ex",
":",
"warn",
"(",
"'Requests HTTP error: {}'",
".",
"format",
"(",
"ex",
")",
")",
"if",
"attempt",
">=",
"5",
":",
"abort",
"(",
"'Too many HTTP errors.'",
")",
"if",
"resp",
"is",
"not",
"None",
":",
"try",
":",
"return",
"resp",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"abort",
"(",
"'Unexpected response from server:\\n\\n{}'",
".",
"format",
"(",
"resp",
".",
"text",
")",
")",
"else",
":",
"abort",
"(",
"\"Couldn't POST to Red October\"",
")"
] |
Generic function to call the RO API
|
[
"Generic",
"function",
"to",
"call",
"the",
"RO",
"API"
] |
cb15a5e2bb735ffce7a84b8413b04faa78c5039c
|
https://github.com/pwyliu/clancy/blob/cb15a5e2bb735ffce7a84b8413b04faa78c5039c/clancy/redoctober.py#L9-L40
|
242,557
|
lvh/axiombench
|
axiombench/update.py
|
benchmark
|
def benchmark(store, n=10000):
"""
Increments an integer count n times.
"""
x = UpdatableItem(store=store, count=0)
for _ in xrange(n):
x.count += 1
|
python
|
def benchmark(store, n=10000):
"""
Increments an integer count n times.
"""
x = UpdatableItem(store=store, count=0)
for _ in xrange(n):
x.count += 1
|
[
"def",
"benchmark",
"(",
"store",
",",
"n",
"=",
"10000",
")",
":",
"x",
"=",
"UpdatableItem",
"(",
"store",
"=",
"store",
",",
"count",
"=",
"0",
")",
"for",
"_",
"in",
"xrange",
"(",
"n",
")",
":",
"x",
".",
"count",
"+=",
"1"
] |
Increments an integer count n times.
|
[
"Increments",
"an",
"integer",
"count",
"n",
"times",
"."
] |
dd783abfde23b0c67d7a74152d372c4c51e112aa
|
https://github.com/lvh/axiombench/blob/dd783abfde23b0c67d7a74152d372c4c51e112aa/axiombench/update.py#L8-L14
|
242,558
|
mayfield/shellish
|
shellish/layout/progress.py
|
progressbar
|
def progressbar(stream, prefix='Loading: ', width=0.5, **options):
""" Generator filter to print a progress bar. """
size = len(stream)
if not size:
return stream
if 'width' not in options:
if width <= 1:
width = round(shutil.get_terminal_size()[0] * width)
options['width'] = width
with ProgressBar(max=size, prefix=prefix, **options) as b:
b.set(0)
for i, x in enumerate(stream, 1):
yield x
b.set(i)
|
python
|
def progressbar(stream, prefix='Loading: ', width=0.5, **options):
""" Generator filter to print a progress bar. """
size = len(stream)
if not size:
return stream
if 'width' not in options:
if width <= 1:
width = round(shutil.get_terminal_size()[0] * width)
options['width'] = width
with ProgressBar(max=size, prefix=prefix, **options) as b:
b.set(0)
for i, x in enumerate(stream, 1):
yield x
b.set(i)
|
[
"def",
"progressbar",
"(",
"stream",
",",
"prefix",
"=",
"'Loading: '",
",",
"width",
"=",
"0.5",
",",
"*",
"*",
"options",
")",
":",
"size",
"=",
"len",
"(",
"stream",
")",
"if",
"not",
"size",
":",
"return",
"stream",
"if",
"'width'",
"not",
"in",
"options",
":",
"if",
"width",
"<=",
"1",
":",
"width",
"=",
"round",
"(",
"shutil",
".",
"get_terminal_size",
"(",
")",
"[",
"0",
"]",
"*",
"width",
")",
"options",
"[",
"'width'",
"]",
"=",
"width",
"with",
"ProgressBar",
"(",
"max",
"=",
"size",
",",
"prefix",
"=",
"prefix",
",",
"*",
"*",
"options",
")",
"as",
"b",
":",
"b",
".",
"set",
"(",
"0",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"stream",
",",
"1",
")",
":",
"yield",
"x",
"b",
".",
"set",
"(",
"i",
")"
] |
Generator filter to print a progress bar.
|
[
"Generator",
"filter",
"to",
"print",
"a",
"progress",
"bar",
"."
] |
df0f0e4612d138c34d8cb99b66ab5b8e47f1414a
|
https://github.com/mayfield/shellish/blob/df0f0e4612d138c34d8cb99b66ab5b8e47f1414a/shellish/layout/progress.py#L79-L92
|
242,559
|
inveniosoftware-contrib/record-recommender
|
record_recommender/utils.py
|
get_week_dates
|
def get_week_dates(year, week, as_timestamp=False):
"""
Get the dates or timestamp of a week in a year.
param year: The year.
param week: The week.
param as_timestamp: Return values as timestamps.
returns: The begin and end of the week as datetime.date or as timestamp.
"""
year = int(year)
week = int(week)
start_date = date(year, 1, 1)
if start_date.weekday() > 3:
start_date = start_date + timedelta(7 - start_date.weekday())
else:
start_date = start_date - timedelta(start_date.weekday())
dlt = timedelta(days=(week-1)*7)
start = start_date + dlt
end = start_date + dlt + timedelta(days=6)
if as_timestamp:
# Add the complete day
one_day = timedelta(days=1).total_seconds() - 0.000001
end_timestamp = time.mktime(end.timetuple()) + one_day
return time.mktime(start.timetuple()), end_timestamp
return start, end
|
python
|
def get_week_dates(year, week, as_timestamp=False):
"""
Get the dates or timestamp of a week in a year.
param year: The year.
param week: The week.
param as_timestamp: Return values as timestamps.
returns: The begin and end of the week as datetime.date or as timestamp.
"""
year = int(year)
week = int(week)
start_date = date(year, 1, 1)
if start_date.weekday() > 3:
start_date = start_date + timedelta(7 - start_date.weekday())
else:
start_date = start_date - timedelta(start_date.weekday())
dlt = timedelta(days=(week-1)*7)
start = start_date + dlt
end = start_date + dlt + timedelta(days=6)
if as_timestamp:
# Add the complete day
one_day = timedelta(days=1).total_seconds() - 0.000001
end_timestamp = time.mktime(end.timetuple()) + one_day
return time.mktime(start.timetuple()), end_timestamp
return start, end
|
[
"def",
"get_week_dates",
"(",
"year",
",",
"week",
",",
"as_timestamp",
"=",
"False",
")",
":",
"year",
"=",
"int",
"(",
"year",
")",
"week",
"=",
"int",
"(",
"week",
")",
"start_date",
"=",
"date",
"(",
"year",
",",
"1",
",",
"1",
")",
"if",
"start_date",
".",
"weekday",
"(",
")",
">",
"3",
":",
"start_date",
"=",
"start_date",
"+",
"timedelta",
"(",
"7",
"-",
"start_date",
".",
"weekday",
"(",
")",
")",
"else",
":",
"start_date",
"=",
"start_date",
"-",
"timedelta",
"(",
"start_date",
".",
"weekday",
"(",
")",
")",
"dlt",
"=",
"timedelta",
"(",
"days",
"=",
"(",
"week",
"-",
"1",
")",
"*",
"7",
")",
"start",
"=",
"start_date",
"+",
"dlt",
"end",
"=",
"start_date",
"+",
"dlt",
"+",
"timedelta",
"(",
"days",
"=",
"6",
")",
"if",
"as_timestamp",
":",
"# Add the complete day",
"one_day",
"=",
"timedelta",
"(",
"days",
"=",
"1",
")",
".",
"total_seconds",
"(",
")",
"-",
"0.000001",
"end_timestamp",
"=",
"time",
".",
"mktime",
"(",
"end",
".",
"timetuple",
"(",
")",
")",
"+",
"one_day",
"return",
"time",
".",
"mktime",
"(",
"start",
".",
"timetuple",
"(",
")",
")",
",",
"end_timestamp",
"return",
"start",
",",
"end"
] |
Get the dates or timestamp of a week in a year.
param year: The year.
param week: The week.
param as_timestamp: Return values as timestamps.
returns: The begin and end of the week as datetime.date or as timestamp.
|
[
"Get",
"the",
"dates",
"or",
"timestamp",
"of",
"a",
"week",
"in",
"a",
"year",
"."
] |
07f71e783369e6373218b5e6ba0bf15901e9251a
|
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/utils.py#L33-L57
|
242,560
|
inveniosoftware-contrib/record-recommender
|
record_recommender/utils.py
|
get_year_week
|
def get_year_week(timestamp):
"""Get the year and week for a given timestamp."""
time_ = datetime.fromtimestamp(timestamp)
year = time_.isocalendar()[0]
week = time_.isocalendar()[1]
return year, week
|
python
|
def get_year_week(timestamp):
"""Get the year and week for a given timestamp."""
time_ = datetime.fromtimestamp(timestamp)
year = time_.isocalendar()[0]
week = time_.isocalendar()[1]
return year, week
|
[
"def",
"get_year_week",
"(",
"timestamp",
")",
":",
"time_",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"timestamp",
")",
"year",
"=",
"time_",
".",
"isocalendar",
"(",
")",
"[",
"0",
"]",
"week",
"=",
"time_",
".",
"isocalendar",
"(",
")",
"[",
"1",
"]",
"return",
"year",
",",
"week"
] |
Get the year and week for a given timestamp.
|
[
"Get",
"the",
"year",
"and",
"week",
"for",
"a",
"given",
"timestamp",
"."
] |
07f71e783369e6373218b5e6ba0bf15901e9251a
|
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/utils.py#L60-L65
|
242,561
|
inveniosoftware-contrib/record-recommender
|
record_recommender/utils.py
|
get_last_weeks
|
def get_last_weeks(number_of_weeks):
"""Get the last weeks."""
time_now = datetime.now()
year = time_now.isocalendar()[0]
week = time_now.isocalendar()[1]
weeks = []
for i in range(0, number_of_weeks):
start = get_week_dates(year, week - i, as_timestamp=True)[0]
n_year, n_week = get_year_week(start)
weeks.append((n_year, n_week))
return weeks
|
python
|
def get_last_weeks(number_of_weeks):
"""Get the last weeks."""
time_now = datetime.now()
year = time_now.isocalendar()[0]
week = time_now.isocalendar()[1]
weeks = []
for i in range(0, number_of_weeks):
start = get_week_dates(year, week - i, as_timestamp=True)[0]
n_year, n_week = get_year_week(start)
weeks.append((n_year, n_week))
return weeks
|
[
"def",
"get_last_weeks",
"(",
"number_of_weeks",
")",
":",
"time_now",
"=",
"datetime",
".",
"now",
"(",
")",
"year",
"=",
"time_now",
".",
"isocalendar",
"(",
")",
"[",
"0",
"]",
"week",
"=",
"time_now",
".",
"isocalendar",
"(",
")",
"[",
"1",
"]",
"weeks",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"number_of_weeks",
")",
":",
"start",
"=",
"get_week_dates",
"(",
"year",
",",
"week",
"-",
"i",
",",
"as_timestamp",
"=",
"True",
")",
"[",
"0",
"]",
"n_year",
",",
"n_week",
"=",
"get_year_week",
"(",
"start",
")",
"weeks",
".",
"append",
"(",
"(",
"n_year",
",",
"n_week",
")",
")",
"return",
"weeks"
] |
Get the last weeks.
|
[
"Get",
"the",
"last",
"weeks",
"."
] |
07f71e783369e6373218b5e6ba0bf15901e9251a
|
https://github.com/inveniosoftware-contrib/record-recommender/blob/07f71e783369e6373218b5e6ba0bf15901e9251a/record_recommender/utils.py#L68-L79
|
242,562
|
Othernet-Project/squery-pg
|
squery_pg/pool.py
|
gevent_wait_callback
|
def gevent_wait_callback(conn, timeout=None):
"""A wait callback useful to allow gevent to work with Psycopg."""
while 1:
state = conn.poll()
if state == extensions.POLL_OK:
break
elif state == extensions.POLL_READ:
wait_read(conn.fileno(), timeout=timeout)
elif state == extensions.POLL_WRITE:
wait_write(conn.fileno(), timeout=timeout)
else:
raise OperationalError(
"Bad result from poll: %r" % state)
|
python
|
def gevent_wait_callback(conn, timeout=None):
"""A wait callback useful to allow gevent to work with Psycopg."""
while 1:
state = conn.poll()
if state == extensions.POLL_OK:
break
elif state == extensions.POLL_READ:
wait_read(conn.fileno(), timeout=timeout)
elif state == extensions.POLL_WRITE:
wait_write(conn.fileno(), timeout=timeout)
else:
raise OperationalError(
"Bad result from poll: %r" % state)
|
[
"def",
"gevent_wait_callback",
"(",
"conn",
",",
"timeout",
"=",
"None",
")",
":",
"while",
"1",
":",
"state",
"=",
"conn",
".",
"poll",
"(",
")",
"if",
"state",
"==",
"extensions",
".",
"POLL_OK",
":",
"break",
"elif",
"state",
"==",
"extensions",
".",
"POLL_READ",
":",
"wait_read",
"(",
"conn",
".",
"fileno",
"(",
")",
",",
"timeout",
"=",
"timeout",
")",
"elif",
"state",
"==",
"extensions",
".",
"POLL_WRITE",
":",
"wait_write",
"(",
"conn",
".",
"fileno",
"(",
")",
",",
"timeout",
"=",
"timeout",
")",
"else",
":",
"raise",
"OperationalError",
"(",
"\"Bad result from poll: %r\"",
"%",
"state",
")"
] |
A wait callback useful to allow gevent to work with Psycopg.
|
[
"A",
"wait",
"callback",
"useful",
"to",
"allow",
"gevent",
"to",
"work",
"with",
"Psycopg",
"."
] |
eaa695c3719e2d2b7e1b049bb58c987c132b6b34
|
https://github.com/Othernet-Project/squery-pg/blob/eaa695c3719e2d2b7e1b049bb58c987c132b6b34/squery_pg/pool.py#L24-L36
|
242,563
|
steenzout/python-sphinx
|
steenzout/sphinx/__init__.py
|
ResourceGenerator.conf
|
def conf(self):
"""Generate the Sphinx `conf.py` configuration file
Returns:
(str): the contents of the `conf.py` file.
"""
return self.env.get_template('conf.py.j2').render(
metadata=self.metadata,
package=self.package)
|
python
|
def conf(self):
"""Generate the Sphinx `conf.py` configuration file
Returns:
(str): the contents of the `conf.py` file.
"""
return self.env.get_template('conf.py.j2').render(
metadata=self.metadata,
package=self.package)
|
[
"def",
"conf",
"(",
"self",
")",
":",
"return",
"self",
".",
"env",
".",
"get_template",
"(",
"'conf.py.j2'",
")",
".",
"render",
"(",
"metadata",
"=",
"self",
".",
"metadata",
",",
"package",
"=",
"self",
".",
"package",
")"
] |
Generate the Sphinx `conf.py` configuration file
Returns:
(str): the contents of the `conf.py` file.
|
[
"Generate",
"the",
"Sphinx",
"conf",
".",
"py",
"configuration",
"file"
] |
b9767195fba74540c385fdf5f94cc4a24bc5e46d
|
https://github.com/steenzout/python-sphinx/blob/b9767195fba74540c385fdf5f94cc4a24bc5e46d/steenzout/sphinx/__init__.py#L42-L50
|
242,564
|
steenzout/python-sphinx
|
steenzout/sphinx/__init__.py
|
ResourceGenerator.makefile
|
def makefile(self):
"""Generate the documentation Makefile.
Returns:
(str): the contents of the `Makefile`.
"""
return self.env.get_template('Makefile.j2').render(
metadata=self.metadata,
package=self.package)
|
python
|
def makefile(self):
"""Generate the documentation Makefile.
Returns:
(str): the contents of the `Makefile`.
"""
return self.env.get_template('Makefile.j2').render(
metadata=self.metadata,
package=self.package)
|
[
"def",
"makefile",
"(",
"self",
")",
":",
"return",
"self",
".",
"env",
".",
"get_template",
"(",
"'Makefile.j2'",
")",
".",
"render",
"(",
"metadata",
"=",
"self",
".",
"metadata",
",",
"package",
"=",
"self",
".",
"package",
")"
] |
Generate the documentation Makefile.
Returns:
(str): the contents of the `Makefile`.
|
[
"Generate",
"the",
"documentation",
"Makefile",
"."
] |
b9767195fba74540c385fdf5f94cc4a24bc5e46d
|
https://github.com/steenzout/python-sphinx/blob/b9767195fba74540c385fdf5f94cc4a24bc5e46d/steenzout/sphinx/__init__.py#L52-L60
|
242,565
|
mrstephenneal/dirutility
|
dirutility/compare.py
|
compare_trees
|
def compare_trees(dir1, dir2):
"""Parse two directories and return lists of unique files"""
paths1 = DirPaths(dir1).walk()
paths2 = DirPaths(dir2).walk()
return unique_venn(paths1, paths2)
|
python
|
def compare_trees(dir1, dir2):
"""Parse two directories and return lists of unique files"""
paths1 = DirPaths(dir1).walk()
paths2 = DirPaths(dir2).walk()
return unique_venn(paths1, paths2)
|
[
"def",
"compare_trees",
"(",
"dir1",
",",
"dir2",
")",
":",
"paths1",
"=",
"DirPaths",
"(",
"dir1",
")",
".",
"walk",
"(",
")",
"paths2",
"=",
"DirPaths",
"(",
"dir2",
")",
".",
"walk",
"(",
")",
"return",
"unique_venn",
"(",
"paths1",
",",
"paths2",
")"
] |
Parse two directories and return lists of unique files
|
[
"Parse",
"two",
"directories",
"and",
"return",
"lists",
"of",
"unique",
"files"
] |
339378659e2d7e09c53acfc51c5df745bb0cd517
|
https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/compare.py#L21-L25
|
242,566
|
openknowledge-archive/datapackage-validate-py
|
datapackage_validate/schema.py
|
Schema.validate
|
def validate(self, data):
'''Validates a data dict against this schema.
Args:
data (dict): The data to be validated.
Raises:
ValidationError: If the data is invalid.
'''
try:
self._validator.validate(data)
except jsonschema.ValidationError as e:
six.raise_from(ValidationError.create_from(e), e)
|
python
|
def validate(self, data):
'''Validates a data dict against this schema.
Args:
data (dict): The data to be validated.
Raises:
ValidationError: If the data is invalid.
'''
try:
self._validator.validate(data)
except jsonschema.ValidationError as e:
six.raise_from(ValidationError.create_from(e), e)
|
[
"def",
"validate",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"self",
".",
"_validator",
".",
"validate",
"(",
"data",
")",
"except",
"jsonschema",
".",
"ValidationError",
"as",
"e",
":",
"six",
".",
"raise_from",
"(",
"ValidationError",
".",
"create_from",
"(",
"e",
")",
",",
"e",
")"
] |
Validates a data dict against this schema.
Args:
data (dict): The data to be validated.
Raises:
ValidationError: If the data is invalid.
|
[
"Validates",
"a",
"data",
"dict",
"against",
"this",
"schema",
"."
] |
5f906bd4e0baa78dfd45f48e7fa3c5d649e6846a
|
https://github.com/openknowledge-archive/datapackage-validate-py/blob/5f906bd4e0baa78dfd45f48e7fa3c5d649e6846a/datapackage_validate/schema.py#L45-L57
|
242,567
|
fangpenlin/pyramid-handy
|
pyramid_handy/tweens/api_headers.py
|
set_version
|
def set_version(request, response):
"""Set version and revision to response
"""
settings = request.registry.settings
resolver = DottedNameResolver()
# get version config
version_header = settings.get(
'api.version_header',
'X-Version',
)
version_header_value = settings.get('api.version_header_value')
if callable(version_header_value):
version_header_value = version_header_value()
elif version_header_value:
version_header_value = resolver.resolve(version_header_value)
# get revision config
revision_header = settings.get(
'api.revision_header',
'X-Revision',
)
revision_header_value = settings.get('api.revision_header_value')
if callable(revision_header_value):
revision_header_value = revision_header_value()
elif revision_header_value:
revision_header_value = resolver.resolve(revision_header_value)
if version_header and version_header_value:
response.headers[str(version_header)] = str(version_header_value)
if revision_header and revision_header_value:
response.headers[str(revision_header)] = str(revision_header_value)
|
python
|
def set_version(request, response):
"""Set version and revision to response
"""
settings = request.registry.settings
resolver = DottedNameResolver()
# get version config
version_header = settings.get(
'api.version_header',
'X-Version',
)
version_header_value = settings.get('api.version_header_value')
if callable(version_header_value):
version_header_value = version_header_value()
elif version_header_value:
version_header_value = resolver.resolve(version_header_value)
# get revision config
revision_header = settings.get(
'api.revision_header',
'X-Revision',
)
revision_header_value = settings.get('api.revision_header_value')
if callable(revision_header_value):
revision_header_value = revision_header_value()
elif revision_header_value:
revision_header_value = resolver.resolve(revision_header_value)
if version_header and version_header_value:
response.headers[str(version_header)] = str(version_header_value)
if revision_header and revision_header_value:
response.headers[str(revision_header)] = str(revision_header_value)
|
[
"def",
"set_version",
"(",
"request",
",",
"response",
")",
":",
"settings",
"=",
"request",
".",
"registry",
".",
"settings",
"resolver",
"=",
"DottedNameResolver",
"(",
")",
"# get version config",
"version_header",
"=",
"settings",
".",
"get",
"(",
"'api.version_header'",
",",
"'X-Version'",
",",
")",
"version_header_value",
"=",
"settings",
".",
"get",
"(",
"'api.version_header_value'",
")",
"if",
"callable",
"(",
"version_header_value",
")",
":",
"version_header_value",
"=",
"version_header_value",
"(",
")",
"elif",
"version_header_value",
":",
"version_header_value",
"=",
"resolver",
".",
"resolve",
"(",
"version_header_value",
")",
"# get revision config",
"revision_header",
"=",
"settings",
".",
"get",
"(",
"'api.revision_header'",
",",
"'X-Revision'",
",",
")",
"revision_header_value",
"=",
"settings",
".",
"get",
"(",
"'api.revision_header_value'",
")",
"if",
"callable",
"(",
"revision_header_value",
")",
":",
"revision_header_value",
"=",
"revision_header_value",
"(",
")",
"elif",
"revision_header_value",
":",
"revision_header_value",
"=",
"resolver",
".",
"resolve",
"(",
"revision_header_value",
")",
"if",
"version_header",
"and",
"version_header_value",
":",
"response",
".",
"headers",
"[",
"str",
"(",
"version_header",
")",
"]",
"=",
"str",
"(",
"version_header_value",
")",
"if",
"revision_header",
"and",
"revision_header_value",
":",
"response",
".",
"headers",
"[",
"str",
"(",
"revision_header",
")",
"]",
"=",
"str",
"(",
"revision_header_value",
")"
] |
Set version and revision to response
|
[
"Set",
"version",
"and",
"revision",
"to",
"response"
] |
e3cbc19224ab1f0a14aab556990bceabd2d1f658
|
https://github.com/fangpenlin/pyramid-handy/blob/e3cbc19224ab1f0a14aab556990bceabd2d1f658/pyramid_handy/tweens/api_headers.py#L7-L39
|
242,568
|
fangpenlin/pyramid-handy
|
pyramid_handy/tweens/api_headers.py
|
api_headers_tween_factory
|
def api_headers_tween_factory(handler, registry):
"""This tween provides necessary API headers
"""
def api_headers_tween(request):
response = handler(request)
set_version(request, response)
set_req_guid(request, response)
return response
return api_headers_tween
|
python
|
def api_headers_tween_factory(handler, registry):
"""This tween provides necessary API headers
"""
def api_headers_tween(request):
response = handler(request)
set_version(request, response)
set_req_guid(request, response)
return response
return api_headers_tween
|
[
"def",
"api_headers_tween_factory",
"(",
"handler",
",",
"registry",
")",
":",
"def",
"api_headers_tween",
"(",
"request",
")",
":",
"response",
"=",
"handler",
"(",
"request",
")",
"set_version",
"(",
"request",
",",
"response",
")",
"set_req_guid",
"(",
"request",
",",
"response",
")",
"return",
"response",
"return",
"api_headers_tween"
] |
This tween provides necessary API headers
|
[
"This",
"tween",
"provides",
"necessary",
"API",
"headers"
] |
e3cbc19224ab1f0a14aab556990bceabd2d1f658
|
https://github.com/fangpenlin/pyramid-handy/blob/e3cbc19224ab1f0a14aab556990bceabd2d1f658/pyramid_handy/tweens/api_headers.py#L62-L73
|
242,569
|
regardscitoyens/lawfactory_utils
|
lawfactory_utils/urls.py
|
clean_url
|
def clean_url(url):
"""
Normalize the url and clean it
>>> clean_url("http://www.assemblee-nationale.fr/15/dossiers/le_nouveau_dossier.asp#deuxieme_partie")
'http://www.assemblee-nationale.fr/dyn/15/dossiers/deuxieme_partie'
>>> clean_url("http://www.conseil-constitutionnel.fr/conseil-constitutionnel/francais/les-decisions/acces-par-date/decisions-depuis-1959/2013/2013-681-dc/decision-n-2013-681-dc-du-5-decembre-2013.138900.html")
'https://www.conseil-constitutionnel.fr/decision/2013/2013681DC.htm'
"""
url = url.strip()
# fix urls like 'pjl09-518.htmlhttp://www.assemblee-nationale.fr/13/ta/ta051`8.asp'
if url.find('https://') > 0:
url = 'https://' + url.split('https://')[1]
if url.find('http://') > 0:
url = 'http://' + url.split('http://')[1]
scheme, netloc, path, params, query, fragment = urlparse(url)
path = path.replace('//', '/')
if 'xtor' in fragment:
fragment = ''
# fix url like http://www.senat.fr/dossier-legislatif/www.conseil-constitutionnel.fr/decision/2012/2012646dc.htm
if 'www.conseil-' in url:
url = urlunparse((scheme, netloc, path, params, query, fragment))
url = 'http://www.conseil-' + url.split('www.conseil-')[1]
return find_stable_link_for_CC_decision(url)
if 'legifrance.gouv.fr' in url:
params = ''
url_jo_params = parse_qs(query)
if 'WAspad' in path:
newurl = get_redirected_url(url)
if url != newurl:
return clean_url(newurl)
if 'cidTexte' in url_jo_params:
query = 'cidTexte=' + url_jo_params['cidTexte'][0]
elif path.endswith('/jo/texte'):
newurl = find_jo_link(url)
if url != newurl:
return clean_url(newurl)
if netloc == 'legifrance.gouv.fr':
netloc = 'www.legifrance.gouv.fr'
if 'jo_pdf.do' in path and 'id' in url_jo_params:
path = 'affichTexte.do'
query = 'cidTexte=' + url_jo_params['id'][0]
# ensure to link initial version of the text and not furtherly modified ones
if query.startswith('cidTexte'):
query += '&categorieLien=id'
path = path.replace('./affichTexte.do', 'affichTexte.do')
if 'senat.fr' in netloc:
path = path.replace('leg/../', '/')
path = path.replace('dossierleg/', 'dossier-legislatif/')
# normalize dosleg url by removing extra url parameters
if 'dossier-legislatif/' in path:
query = ''
fragment = ''
if netloc == 'webdim':
netloc = 'www.assemblee-nationale.fr'
# force https
if 'assemblee-nationale.fr' not in netloc and 'conseil-constitutionnel.fr' not in netloc:
scheme = 'https'
# url like http://www.assemblee-nationale.fr/13/projets/pl2727.asp2727
if 'assemblee-nationale.fr' in url:
path = re_clean_ending_digits.sub(r"\1", path)
if '/dossiers/' in path:
url = urlunparse((scheme, netloc, path, params, query, fragment))
legislature, slug = parse_national_assembly_url(url)
if legislature and slug:
template = AN_OLD_URL_TEMPLATE
if legislature > 14:
template = AN_NEW_URL_TEMPLATE
return template.format(legislature=legislature, slug=slug)
return urlunparse((scheme, netloc, path, params, query, fragment))
|
python
|
def clean_url(url):
"""
Normalize the url and clean it
>>> clean_url("http://www.assemblee-nationale.fr/15/dossiers/le_nouveau_dossier.asp#deuxieme_partie")
'http://www.assemblee-nationale.fr/dyn/15/dossiers/deuxieme_partie'
>>> clean_url("http://www.conseil-constitutionnel.fr/conseil-constitutionnel/francais/les-decisions/acces-par-date/decisions-depuis-1959/2013/2013-681-dc/decision-n-2013-681-dc-du-5-decembre-2013.138900.html")
'https://www.conseil-constitutionnel.fr/decision/2013/2013681DC.htm'
"""
url = url.strip()
# fix urls like 'pjl09-518.htmlhttp://www.assemblee-nationale.fr/13/ta/ta051`8.asp'
if url.find('https://') > 0:
url = 'https://' + url.split('https://')[1]
if url.find('http://') > 0:
url = 'http://' + url.split('http://')[1]
scheme, netloc, path, params, query, fragment = urlparse(url)
path = path.replace('//', '/')
if 'xtor' in fragment:
fragment = ''
# fix url like http://www.senat.fr/dossier-legislatif/www.conseil-constitutionnel.fr/decision/2012/2012646dc.htm
if 'www.conseil-' in url:
url = urlunparse((scheme, netloc, path, params, query, fragment))
url = 'http://www.conseil-' + url.split('www.conseil-')[1]
return find_stable_link_for_CC_decision(url)
if 'legifrance.gouv.fr' in url:
params = ''
url_jo_params = parse_qs(query)
if 'WAspad' in path:
newurl = get_redirected_url(url)
if url != newurl:
return clean_url(newurl)
if 'cidTexte' in url_jo_params:
query = 'cidTexte=' + url_jo_params['cidTexte'][0]
elif path.endswith('/jo/texte'):
newurl = find_jo_link(url)
if url != newurl:
return clean_url(newurl)
if netloc == 'legifrance.gouv.fr':
netloc = 'www.legifrance.gouv.fr'
if 'jo_pdf.do' in path and 'id' in url_jo_params:
path = 'affichTexte.do'
query = 'cidTexte=' + url_jo_params['id'][0]
# ensure to link initial version of the text and not furtherly modified ones
if query.startswith('cidTexte'):
query += '&categorieLien=id'
path = path.replace('./affichTexte.do', 'affichTexte.do')
if 'senat.fr' in netloc:
path = path.replace('leg/../', '/')
path = path.replace('dossierleg/', 'dossier-legislatif/')
# normalize dosleg url by removing extra url parameters
if 'dossier-legislatif/' in path:
query = ''
fragment = ''
if netloc == 'webdim':
netloc = 'www.assemblee-nationale.fr'
# force https
if 'assemblee-nationale.fr' not in netloc and 'conseil-constitutionnel.fr' not in netloc:
scheme = 'https'
# url like http://www.assemblee-nationale.fr/13/projets/pl2727.asp2727
if 'assemblee-nationale.fr' in url:
path = re_clean_ending_digits.sub(r"\1", path)
if '/dossiers/' in path:
url = urlunparse((scheme, netloc, path, params, query, fragment))
legislature, slug = parse_national_assembly_url(url)
if legislature and slug:
template = AN_OLD_URL_TEMPLATE
if legislature > 14:
template = AN_NEW_URL_TEMPLATE
return template.format(legislature=legislature, slug=slug)
return urlunparse((scheme, netloc, path, params, query, fragment))
|
[
"def",
"clean_url",
"(",
"url",
")",
":",
"url",
"=",
"url",
".",
"strip",
"(",
")",
"# fix urls like 'pjl09-518.htmlhttp://www.assemblee-nationale.fr/13/ta/ta051`8.asp'",
"if",
"url",
".",
"find",
"(",
"'https://'",
")",
">",
"0",
":",
"url",
"=",
"'https://'",
"+",
"url",
".",
"split",
"(",
"'https://'",
")",
"[",
"1",
"]",
"if",
"url",
".",
"find",
"(",
"'http://'",
")",
">",
"0",
":",
"url",
"=",
"'http://'",
"+",
"url",
".",
"split",
"(",
"'http://'",
")",
"[",
"1",
"]",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
"=",
"urlparse",
"(",
"url",
")",
"path",
"=",
"path",
".",
"replace",
"(",
"'//'",
",",
"'/'",
")",
"if",
"'xtor'",
"in",
"fragment",
":",
"fragment",
"=",
"''",
"# fix url like http://www.senat.fr/dossier-legislatif/www.conseil-constitutionnel.fr/decision/2012/2012646dc.htm",
"if",
"'www.conseil-'",
"in",
"url",
":",
"url",
"=",
"urlunparse",
"(",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
")",
")",
"url",
"=",
"'http://www.conseil-'",
"+",
"url",
".",
"split",
"(",
"'www.conseil-'",
")",
"[",
"1",
"]",
"return",
"find_stable_link_for_CC_decision",
"(",
"url",
")",
"if",
"'legifrance.gouv.fr'",
"in",
"url",
":",
"params",
"=",
"''",
"url_jo_params",
"=",
"parse_qs",
"(",
"query",
")",
"if",
"'WAspad'",
"in",
"path",
":",
"newurl",
"=",
"get_redirected_url",
"(",
"url",
")",
"if",
"url",
"!=",
"newurl",
":",
"return",
"clean_url",
"(",
"newurl",
")",
"if",
"'cidTexte'",
"in",
"url_jo_params",
":",
"query",
"=",
"'cidTexte='",
"+",
"url_jo_params",
"[",
"'cidTexte'",
"]",
"[",
"0",
"]",
"elif",
"path",
".",
"endswith",
"(",
"'/jo/texte'",
")",
":",
"newurl",
"=",
"find_jo_link",
"(",
"url",
")",
"if",
"url",
"!=",
"newurl",
":",
"return",
"clean_url",
"(",
"newurl",
")",
"if",
"netloc",
"==",
"'legifrance.gouv.fr'",
":",
"netloc",
"=",
"'www.legifrance.gouv.fr'",
"if",
"'jo_pdf.do'",
"in",
"path",
"and",
"'id'",
"in",
"url_jo_params",
":",
"path",
"=",
"'affichTexte.do'",
"query",
"=",
"'cidTexte='",
"+",
"url_jo_params",
"[",
"'id'",
"]",
"[",
"0",
"]",
"# ensure to link initial version of the text and not furtherly modified ones",
"if",
"query",
".",
"startswith",
"(",
"'cidTexte'",
")",
":",
"query",
"+=",
"'&categorieLien=id'",
"path",
"=",
"path",
".",
"replace",
"(",
"'./affichTexte.do'",
",",
"'affichTexte.do'",
")",
"if",
"'senat.fr'",
"in",
"netloc",
":",
"path",
"=",
"path",
".",
"replace",
"(",
"'leg/../'",
",",
"'/'",
")",
"path",
"=",
"path",
".",
"replace",
"(",
"'dossierleg/'",
",",
"'dossier-legislatif/'",
")",
"# normalize dosleg url by removing extra url parameters",
"if",
"'dossier-legislatif/'",
"in",
"path",
":",
"query",
"=",
"''",
"fragment",
"=",
"''",
"if",
"netloc",
"==",
"'webdim'",
":",
"netloc",
"=",
"'www.assemblee-nationale.fr'",
"# force https",
"if",
"'assemblee-nationale.fr'",
"not",
"in",
"netloc",
"and",
"'conseil-constitutionnel.fr'",
"not",
"in",
"netloc",
":",
"scheme",
"=",
"'https'",
"# url like http://www.assemblee-nationale.fr/13/projets/pl2727.asp2727",
"if",
"'assemblee-nationale.fr'",
"in",
"url",
":",
"path",
"=",
"re_clean_ending_digits",
".",
"sub",
"(",
"r\"\\1\"",
",",
"path",
")",
"if",
"'/dossiers/'",
"in",
"path",
":",
"url",
"=",
"urlunparse",
"(",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
")",
")",
"legislature",
",",
"slug",
"=",
"parse_national_assembly_url",
"(",
"url",
")",
"if",
"legislature",
"and",
"slug",
":",
"template",
"=",
"AN_OLD_URL_TEMPLATE",
"if",
"legislature",
">",
"14",
":",
"template",
"=",
"AN_NEW_URL_TEMPLATE",
"return",
"template",
".",
"format",
"(",
"legislature",
"=",
"legislature",
",",
"slug",
"=",
"slug",
")",
"return",
"urlunparse",
"(",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
")",
")"
] |
Normalize the url and clean it
>>> clean_url("http://www.assemblee-nationale.fr/15/dossiers/le_nouveau_dossier.asp#deuxieme_partie")
'http://www.assemblee-nationale.fr/dyn/15/dossiers/deuxieme_partie'
>>> clean_url("http://www.conseil-constitutionnel.fr/conseil-constitutionnel/francais/les-decisions/acces-par-date/decisions-depuis-1959/2013/2013-681-dc/decision-n-2013-681-dc-du-5-decembre-2013.138900.html")
'https://www.conseil-constitutionnel.fr/decision/2013/2013681DC.htm'
|
[
"Normalize",
"the",
"url",
"and",
"clean",
"it"
] |
d8565c5216f9ef8ce7c91a2409782f2d2636f67e
|
https://github.com/regardscitoyens/lawfactory_utils/blob/d8565c5216f9ef8ce7c91a2409782f2d2636f67e/lawfactory_utils/urls.py#L141-L227
|
242,570
|
regardscitoyens/lawfactory_utils
|
lawfactory_utils/urls.py
|
parse_national_assembly_url
|
def parse_national_assembly_url(url_an):
"""Returns the slug and the legislature of an AN url
>>> # old format
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/14/dossiers/devoir_vigilance_entreprises_donneuses_ordre.asp")
(14, 'devoir_vigilance_entreprises_donneuses_ordre')
>>> # new format
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/dyn/15/dossiers/retablissement_confiance_action_publique")
(15, 'retablissement_confiance_action_publique')
>>> # sometimes there's a linked subsection, it's the real dosleg ID, we only use it if we are in the 15th legislature
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/14/dossiers/le_dossier.asp#deuxieme_partie")
(14, 'le_dossier')
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/15/dossiers/le_nouveau_dossier.asp#deuxieme_partie")
(15, 'deuxieme_partie')
>>> # some dossier-like urls are not actual dossiers
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/14/dossiers/motion_referendaire_2097.pdf")
(14, None)
"""
legislature_match = re.search(r"\.fr/(dyn/)?(\d+)/", url_an)
if legislature_match:
legislature = int(legislature_match.group(2))
else:
legislature = None
slug = None
slug_match = re.search(r"/([\w_\-]*)(?:\.asp)?(?:#([\w_\-]*))?$", url_an)
if slug_match:
if legislature and legislature > 14:
slug = slug_match.group(2) or slug_match.group(1)
else:
slug = slug_match.group(1)
return legislature, slug
|
python
|
def parse_national_assembly_url(url_an):
"""Returns the slug and the legislature of an AN url
>>> # old format
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/14/dossiers/devoir_vigilance_entreprises_donneuses_ordre.asp")
(14, 'devoir_vigilance_entreprises_donneuses_ordre')
>>> # new format
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/dyn/15/dossiers/retablissement_confiance_action_publique")
(15, 'retablissement_confiance_action_publique')
>>> # sometimes there's a linked subsection, it's the real dosleg ID, we only use it if we are in the 15th legislature
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/14/dossiers/le_dossier.asp#deuxieme_partie")
(14, 'le_dossier')
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/15/dossiers/le_nouveau_dossier.asp#deuxieme_partie")
(15, 'deuxieme_partie')
>>> # some dossier-like urls are not actual dossiers
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/14/dossiers/motion_referendaire_2097.pdf")
(14, None)
"""
legislature_match = re.search(r"\.fr/(dyn/)?(\d+)/", url_an)
if legislature_match:
legislature = int(legislature_match.group(2))
else:
legislature = None
slug = None
slug_match = re.search(r"/([\w_\-]*)(?:\.asp)?(?:#([\w_\-]*))?$", url_an)
if slug_match:
if legislature and legislature > 14:
slug = slug_match.group(2) or slug_match.group(1)
else:
slug = slug_match.group(1)
return legislature, slug
|
[
"def",
"parse_national_assembly_url",
"(",
"url_an",
")",
":",
"legislature_match",
"=",
"re",
".",
"search",
"(",
"r\"\\.fr/(dyn/)?(\\d+)/\"",
",",
"url_an",
")",
"if",
"legislature_match",
":",
"legislature",
"=",
"int",
"(",
"legislature_match",
".",
"group",
"(",
"2",
")",
")",
"else",
":",
"legislature",
"=",
"None",
"slug",
"=",
"None",
"slug_match",
"=",
"re",
".",
"search",
"(",
"r\"/([\\w_\\-]*)(?:\\.asp)?(?:#([\\w_\\-]*))?$\"",
",",
"url_an",
")",
"if",
"slug_match",
":",
"if",
"legislature",
"and",
"legislature",
">",
"14",
":",
"slug",
"=",
"slug_match",
".",
"group",
"(",
"2",
")",
"or",
"slug_match",
".",
"group",
"(",
"1",
")",
"else",
":",
"slug",
"=",
"slug_match",
".",
"group",
"(",
"1",
")",
"return",
"legislature",
",",
"slug"
] |
Returns the slug and the legislature of an AN url
>>> # old format
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/14/dossiers/devoir_vigilance_entreprises_donneuses_ordre.asp")
(14, 'devoir_vigilance_entreprises_donneuses_ordre')
>>> # new format
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/dyn/15/dossiers/retablissement_confiance_action_publique")
(15, 'retablissement_confiance_action_publique')
>>> # sometimes there's a linked subsection, it's the real dosleg ID, we only use it if we are in the 15th legislature
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/14/dossiers/le_dossier.asp#deuxieme_partie")
(14, 'le_dossier')
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/15/dossiers/le_nouveau_dossier.asp#deuxieme_partie")
(15, 'deuxieme_partie')
>>> # some dossier-like urls are not actual dossiers
>>> parse_national_assembly_url("http://www.assemblee-nationale.fr/14/dossiers/motion_referendaire_2097.pdf")
(14, None)
|
[
"Returns",
"the",
"slug",
"and",
"the",
"legislature",
"of",
"an",
"AN",
"url"
] |
d8565c5216f9ef8ce7c91a2409782f2d2636f67e
|
https://github.com/regardscitoyens/lawfactory_utils/blob/d8565c5216f9ef8ce7c91a2409782f2d2636f67e/lawfactory_utils/urls.py#L230-L263
|
242,571
|
jhazelwo/python-fileasobj
|
fileasobj/__init__.py
|
FileAsObj.read
|
def read(self, given_file):
"""
Read given_file to self.contents
Will ignoring duplicate lines if self.unique is True
Will sort self.contents after reading file if self.sorted is True
"""
if self.unique is not False and self.unique is not True:
raise AttributeError("Attribute 'unique' is not True or False.")
self.filename = str.strip(given_file)
self.log('Read-only opening {0}'.format(self.filename))
with open(self.filename, 'r') as handle:
for line in handle:
line = line.rstrip('\r\n')
if line is None:
line = '' # Blank lines that were just \n become None so convert them to empty string.
if self.unique is False or line not in self.contents:
self.contents.append(line)
if self.sorted:
self.sort()
self.log('Read {0} lines.'.format(len(self.contents)))
return True
|
python
|
def read(self, given_file):
"""
Read given_file to self.contents
Will ignoring duplicate lines if self.unique is True
Will sort self.contents after reading file if self.sorted is True
"""
if self.unique is not False and self.unique is not True:
raise AttributeError("Attribute 'unique' is not True or False.")
self.filename = str.strip(given_file)
self.log('Read-only opening {0}'.format(self.filename))
with open(self.filename, 'r') as handle:
for line in handle:
line = line.rstrip('\r\n')
if line is None:
line = '' # Blank lines that were just \n become None so convert them to empty string.
if self.unique is False or line not in self.contents:
self.contents.append(line)
if self.sorted:
self.sort()
self.log('Read {0} lines.'.format(len(self.contents)))
return True
|
[
"def",
"read",
"(",
"self",
",",
"given_file",
")",
":",
"if",
"self",
".",
"unique",
"is",
"not",
"False",
"and",
"self",
".",
"unique",
"is",
"not",
"True",
":",
"raise",
"AttributeError",
"(",
"\"Attribute 'unique' is not True or False.\"",
")",
"self",
".",
"filename",
"=",
"str",
".",
"strip",
"(",
"given_file",
")",
"self",
".",
"log",
"(",
"'Read-only opening {0}'",
".",
"format",
"(",
"self",
".",
"filename",
")",
")",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'r'",
")",
"as",
"handle",
":",
"for",
"line",
"in",
"handle",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
"'\\r\\n'",
")",
"if",
"line",
"is",
"None",
":",
"line",
"=",
"''",
"# Blank lines that were just \\n become None so convert them to empty string.",
"if",
"self",
".",
"unique",
"is",
"False",
"or",
"line",
"not",
"in",
"self",
".",
"contents",
":",
"self",
".",
"contents",
".",
"append",
"(",
"line",
")",
"if",
"self",
".",
"sorted",
":",
"self",
".",
"sort",
"(",
")",
"self",
".",
"log",
"(",
"'Read {0} lines.'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"contents",
")",
")",
")",
"return",
"True"
] |
Read given_file to self.contents
Will ignoring duplicate lines if self.unique is True
Will sort self.contents after reading file if self.sorted is True
|
[
"Read",
"given_file",
"to",
"self",
".",
"contents",
"Will",
"ignoring",
"duplicate",
"lines",
"if",
"self",
".",
"unique",
"is",
"True",
"Will",
"sort",
"self",
".",
"contents",
"after",
"reading",
"file",
"if",
"self",
".",
"sorted",
"is",
"True"
] |
4bdbb575e75da830b88d10d0c1020d787ceba44d
|
https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/fileasobj/__init__.py#L89-L109
|
242,572
|
jhazelwo/python-fileasobj
|
fileasobj/__init__.py
|
FileAsObj.check
|
def check(self, line):
"""
Find first occurrence of 'line' in file.
This searches each line as a whole, if you want to see if a substring is in a line, use .grep() or .egrep()
If found, return the line; this makes it easier to chain methods.
:param line: String; whole line to find.
:return: String or False.
"""
if not isinstance(line, str):
raise TypeError("Parameter 'line' not a 'string', is {0}".format(type(line)))
if line in self.contents:
return line
return False
|
python
|
def check(self, line):
"""
Find first occurrence of 'line' in file.
This searches each line as a whole, if you want to see if a substring is in a line, use .grep() or .egrep()
If found, return the line; this makes it easier to chain methods.
:param line: String; whole line to find.
:return: String or False.
"""
if not isinstance(line, str):
raise TypeError("Parameter 'line' not a 'string', is {0}".format(type(line)))
if line in self.contents:
return line
return False
|
[
"def",
"check",
"(",
"self",
",",
"line",
")",
":",
"if",
"not",
"isinstance",
"(",
"line",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Parameter 'line' not a 'string', is {0}\"",
".",
"format",
"(",
"type",
"(",
"line",
")",
")",
")",
"if",
"line",
"in",
"self",
".",
"contents",
":",
"return",
"line",
"return",
"False"
] |
Find first occurrence of 'line' in file.
This searches each line as a whole, if you want to see if a substring is in a line, use .grep() or .egrep()
If found, return the line; this makes it easier to chain methods.
:param line: String; whole line to find.
:return: String or False.
|
[
"Find",
"first",
"occurrence",
"of",
"line",
"in",
"file",
"."
] |
4bdbb575e75da830b88d10d0c1020d787ceba44d
|
https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/fileasobj/__init__.py#L111-L126
|
242,573
|
jhazelwo/python-fileasobj
|
fileasobj/__init__.py
|
FileAsObj.add
|
def add(self, line):
"""
Append 'line' to contents
where 'line' is an entire line or a list of lines.
If self.unique is False it will add regardless of contents.
Multi-line strings are converted to a list delimited by new lines.
:param line: String or List of Strings; arbitrary string(s) to append to file contents.
:return: Boolean; whether contents were changed during this method call.
"""
if self.unique is not False and self.unique is not True:
raise AttributeError("Attribute 'unique' is not True or False.")
self.log('add({0}); unique={1}'.format(line, self.unique))
if line is False:
return False
if isinstance(line, str):
line = line.split('\n')
if not isinstance(line, list):
raise TypeError("Parameter 'line' not a 'string' or 'list', is {0}".format(type(line)))
local_changes = False
for this in line:
if self.unique is False or this not in self.contents:
self.contents.append(this)
self.changed = local_changes = True
if self.sorted and local_changes:
self.sort()
return local_changes
|
python
|
def add(self, line):
"""
Append 'line' to contents
where 'line' is an entire line or a list of lines.
If self.unique is False it will add regardless of contents.
Multi-line strings are converted to a list delimited by new lines.
:param line: String or List of Strings; arbitrary string(s) to append to file contents.
:return: Boolean; whether contents were changed during this method call.
"""
if self.unique is not False and self.unique is not True:
raise AttributeError("Attribute 'unique' is not True or False.")
self.log('add({0}); unique={1}'.format(line, self.unique))
if line is False:
return False
if isinstance(line, str):
line = line.split('\n')
if not isinstance(line, list):
raise TypeError("Parameter 'line' not a 'string' or 'list', is {0}".format(type(line)))
local_changes = False
for this in line:
if self.unique is False or this not in self.contents:
self.contents.append(this)
self.changed = local_changes = True
if self.sorted and local_changes:
self.sort()
return local_changes
|
[
"def",
"add",
"(",
"self",
",",
"line",
")",
":",
"if",
"self",
".",
"unique",
"is",
"not",
"False",
"and",
"self",
".",
"unique",
"is",
"not",
"True",
":",
"raise",
"AttributeError",
"(",
"\"Attribute 'unique' is not True or False.\"",
")",
"self",
".",
"log",
"(",
"'add({0}); unique={1}'",
".",
"format",
"(",
"line",
",",
"self",
".",
"unique",
")",
")",
"if",
"line",
"is",
"False",
":",
"return",
"False",
"if",
"isinstance",
"(",
"line",
",",
"str",
")",
":",
"line",
"=",
"line",
".",
"split",
"(",
"'\\n'",
")",
"if",
"not",
"isinstance",
"(",
"line",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"Parameter 'line' not a 'string' or 'list', is {0}\"",
".",
"format",
"(",
"type",
"(",
"line",
")",
")",
")",
"local_changes",
"=",
"False",
"for",
"this",
"in",
"line",
":",
"if",
"self",
".",
"unique",
"is",
"False",
"or",
"this",
"not",
"in",
"self",
".",
"contents",
":",
"self",
".",
"contents",
".",
"append",
"(",
"this",
")",
"self",
".",
"changed",
"=",
"local_changes",
"=",
"True",
"if",
"self",
".",
"sorted",
"and",
"local_changes",
":",
"self",
".",
"sort",
"(",
")",
"return",
"local_changes"
] |
Append 'line' to contents
where 'line' is an entire line or a list of lines.
If self.unique is False it will add regardless of contents.
Multi-line strings are converted to a list delimited by new lines.
:param line: String or List of Strings; arbitrary string(s) to append to file contents.
:return: Boolean; whether contents were changed during this method call.
|
[
"Append",
"line",
"to",
"contents",
"where",
"line",
"is",
"an",
"entire",
"line",
"or",
"a",
"list",
"of",
"lines",
"."
] |
4bdbb575e75da830b88d10d0c1020d787ceba44d
|
https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/fileasobj/__init__.py#L128-L156
|
242,574
|
jhazelwo/python-fileasobj
|
fileasobj/__init__.py
|
FileAsObj.rm
|
def rm(self, line):
"""
Remove all occurrences of 'line' from contents
where 'line' is an entire line or a list of lines.
Return true if the file was changed by rm(), False otherwise.
Multi-line strings are converted to a list delimited by new lines.
:param line: String, or List of Strings; each string represents an entire line to be removed from file.
:return: Boolean, whether contents were changed.
"""
self.log('rm({0})'.format(line))
if line is False:
return False
if isinstance(line, str):
line = line.split('\n')
if not isinstance(line, list):
raise TypeError("Parameter 'line' not a 'string' or 'list', is {0}".format(type(line)))
local_changes = False
for this in line:
if this in self.contents:
while this in self.contents:
self.log('Removed "{0}" from position {1}'.format(this, self.contents.index(this)))
self.contents.remove(this)
self.changed = local_changes = True
else:
self.log('"{0}" not in {1}'.format(this, self.filename))
if self.sorted and local_changes:
self.sort()
return local_changes
|
python
|
def rm(self, line):
"""
Remove all occurrences of 'line' from contents
where 'line' is an entire line or a list of lines.
Return true if the file was changed by rm(), False otherwise.
Multi-line strings are converted to a list delimited by new lines.
:param line: String, or List of Strings; each string represents an entire line to be removed from file.
:return: Boolean, whether contents were changed.
"""
self.log('rm({0})'.format(line))
if line is False:
return False
if isinstance(line, str):
line = line.split('\n')
if not isinstance(line, list):
raise TypeError("Parameter 'line' not a 'string' or 'list', is {0}".format(type(line)))
local_changes = False
for this in line:
if this in self.contents:
while this in self.contents:
self.log('Removed "{0}" from position {1}'.format(this, self.contents.index(this)))
self.contents.remove(this)
self.changed = local_changes = True
else:
self.log('"{0}" not in {1}'.format(this, self.filename))
if self.sorted and local_changes:
self.sort()
return local_changes
|
[
"def",
"rm",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"log",
"(",
"'rm({0})'",
".",
"format",
"(",
"line",
")",
")",
"if",
"line",
"is",
"False",
":",
"return",
"False",
"if",
"isinstance",
"(",
"line",
",",
"str",
")",
":",
"line",
"=",
"line",
".",
"split",
"(",
"'\\n'",
")",
"if",
"not",
"isinstance",
"(",
"line",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"Parameter 'line' not a 'string' or 'list', is {0}\"",
".",
"format",
"(",
"type",
"(",
"line",
")",
")",
")",
"local_changes",
"=",
"False",
"for",
"this",
"in",
"line",
":",
"if",
"this",
"in",
"self",
".",
"contents",
":",
"while",
"this",
"in",
"self",
".",
"contents",
":",
"self",
".",
"log",
"(",
"'Removed \"{0}\" from position {1}'",
".",
"format",
"(",
"this",
",",
"self",
".",
"contents",
".",
"index",
"(",
"this",
")",
")",
")",
"self",
".",
"contents",
".",
"remove",
"(",
"this",
")",
"self",
".",
"changed",
"=",
"local_changes",
"=",
"True",
"else",
":",
"self",
".",
"log",
"(",
"'\"{0}\" not in {1}'",
".",
"format",
"(",
"this",
",",
"self",
".",
"filename",
")",
")",
"if",
"self",
".",
"sorted",
"and",
"local_changes",
":",
"self",
".",
"sort",
"(",
")",
"return",
"local_changes"
] |
Remove all occurrences of 'line' from contents
where 'line' is an entire line or a list of lines.
Return true if the file was changed by rm(), False otherwise.
Multi-line strings are converted to a list delimited by new lines.
:param line: String, or List of Strings; each string represents an entire line to be removed from file.
:return: Boolean, whether contents were changed.
|
[
"Remove",
"all",
"occurrences",
"of",
"line",
"from",
"contents",
"where",
"line",
"is",
"an",
"entire",
"line",
"or",
"a",
"list",
"of",
"lines",
"."
] |
4bdbb575e75da830b88d10d0c1020d787ceba44d
|
https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/fileasobj/__init__.py#L158-L188
|
242,575
|
jhazelwo/python-fileasobj
|
fileasobj/__init__.py
|
FileAsObj.replace
|
def replace(self, old, new):
"""
Replace all lines of file that match 'old' with 'new'
Will replace duplicates if found.
:param old: String, List of Strings, a multi-line String, or False; what to replace.
:param new: String; what to use as replacement.
:return: Boolean; whether contents changed during method call.
"""
self.log('replace({0}, {1})'.format(old, new))
if old is False:
return False
if isinstance(old, str):
old = old.split('\n')
if not isinstance(old, list):
raise TypeError("Parameter 'old' not a 'string' or 'list', is {0}".format(type(old)))
if not isinstance(new, str):
raise TypeError("Parameter 'new' not a 'string', is {0}".format(type(new)))
local_changes = False
for this in old:
if this in self.contents:
while this in self.contents:
index = self.contents.index(this)
self.changed = local_changes = True
self.contents.remove(this)
self.contents.insert(index, new)
self.log('Replaced "{0}" with "{1}" at line {2}'.format(this, new, index))
else:
self.log('"{0}" not in {1}'.format(this, self.filename))
return local_changes
|
python
|
def replace(self, old, new):
"""
Replace all lines of file that match 'old' with 'new'
Will replace duplicates if found.
:param old: String, List of Strings, a multi-line String, or False; what to replace.
:param new: String; what to use as replacement.
:return: Boolean; whether contents changed during method call.
"""
self.log('replace({0}, {1})'.format(old, new))
if old is False:
return False
if isinstance(old, str):
old = old.split('\n')
if not isinstance(old, list):
raise TypeError("Parameter 'old' not a 'string' or 'list', is {0}".format(type(old)))
if not isinstance(new, str):
raise TypeError("Parameter 'new' not a 'string', is {0}".format(type(new)))
local_changes = False
for this in old:
if this in self.contents:
while this in self.contents:
index = self.contents.index(this)
self.changed = local_changes = True
self.contents.remove(this)
self.contents.insert(index, new)
self.log('Replaced "{0}" with "{1}" at line {2}'.format(this, new, index))
else:
self.log('"{0}" not in {1}'.format(this, self.filename))
return local_changes
|
[
"def",
"replace",
"(",
"self",
",",
"old",
",",
"new",
")",
":",
"self",
".",
"log",
"(",
"'replace({0}, {1})'",
".",
"format",
"(",
"old",
",",
"new",
")",
")",
"if",
"old",
"is",
"False",
":",
"return",
"False",
"if",
"isinstance",
"(",
"old",
",",
"str",
")",
":",
"old",
"=",
"old",
".",
"split",
"(",
"'\\n'",
")",
"if",
"not",
"isinstance",
"(",
"old",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"Parameter 'old' not a 'string' or 'list', is {0}\"",
".",
"format",
"(",
"type",
"(",
"old",
")",
")",
")",
"if",
"not",
"isinstance",
"(",
"new",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Parameter 'new' not a 'string', is {0}\"",
".",
"format",
"(",
"type",
"(",
"new",
")",
")",
")",
"local_changes",
"=",
"False",
"for",
"this",
"in",
"old",
":",
"if",
"this",
"in",
"self",
".",
"contents",
":",
"while",
"this",
"in",
"self",
".",
"contents",
":",
"index",
"=",
"self",
".",
"contents",
".",
"index",
"(",
"this",
")",
"self",
".",
"changed",
"=",
"local_changes",
"=",
"True",
"self",
".",
"contents",
".",
"remove",
"(",
"this",
")",
"self",
".",
"contents",
".",
"insert",
"(",
"index",
",",
"new",
")",
"self",
".",
"log",
"(",
"'Replaced \"{0}\" with \"{1}\" at line {2}'",
".",
"format",
"(",
"this",
",",
"new",
",",
"index",
")",
")",
"else",
":",
"self",
".",
"log",
"(",
"'\"{0}\" not in {1}'",
".",
"format",
"(",
"this",
",",
"self",
".",
"filename",
")",
")",
"return",
"local_changes"
] |
Replace all lines of file that match 'old' with 'new'
Will replace duplicates if found.
:param old: String, List of Strings, a multi-line String, or False; what to replace.
:param new: String; what to use as replacement.
:return: Boolean; whether contents changed during method call.
|
[
"Replace",
"all",
"lines",
"of",
"file",
"that",
"match",
"old",
"with",
"new"
] |
4bdbb575e75da830b88d10d0c1020d787ceba44d
|
https://github.com/jhazelwo/python-fileasobj/blob/4bdbb575e75da830b88d10d0c1020d787ceba44d/fileasobj/__init__.py#L245-L276
|
242,576
|
Archived-Object/ligament
|
ligament/helpers.py
|
partition
|
def partition(pred, iterable):
""" split the results of an iterable based on a predicate """
trues = []
falses = []
for item in iterable:
if pred(item):
trues.append(item)
else:
falses.append(item)
return trues, falses
|
python
|
def partition(pred, iterable):
""" split the results of an iterable based on a predicate """
trues = []
falses = []
for item in iterable:
if pred(item):
trues.append(item)
else:
falses.append(item)
return trues, falses
|
[
"def",
"partition",
"(",
"pred",
",",
"iterable",
")",
":",
"trues",
"=",
"[",
"]",
"falses",
"=",
"[",
"]",
"for",
"item",
"in",
"iterable",
":",
"if",
"pred",
"(",
"item",
")",
":",
"trues",
".",
"append",
"(",
"item",
")",
"else",
":",
"falses",
".",
"append",
"(",
"item",
")",
"return",
"trues",
",",
"falses"
] |
split the results of an iterable based on a predicate
|
[
"split",
"the",
"results",
"of",
"an",
"iterable",
"based",
"on",
"a",
"predicate"
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/helpers.py#L17-L26
|
242,577
|
Archived-Object/ligament
|
ligament/helpers.py
|
zip_with_output
|
def zip_with_output(skip_args=[]):
"""decorater that zips the input of a function with its output
only zips positional arguments.
skip_args : list
a list of indexes of arguments to exclude from the skip
@zip_with_output(skip_args=[0])
def foo(bar, baz):
return baz
will decorate foo s.t.
foo(x, y) = y
"""
def decorator(fn):
def wrapped(*args, **vargs):
g = [arg for i, arg in enumerate(args) if i not in skip_args]
if len(g) == 1:
return(g[0], fn(*args, **vargs))
else:
return (g, fn(*args, **vargs))
return wrapped
return decorator
|
python
|
def zip_with_output(skip_args=[]):
"""decorater that zips the input of a function with its output
only zips positional arguments.
skip_args : list
a list of indexes of arguments to exclude from the skip
@zip_with_output(skip_args=[0])
def foo(bar, baz):
return baz
will decorate foo s.t.
foo(x, y) = y
"""
def decorator(fn):
def wrapped(*args, **vargs):
g = [arg for i, arg in enumerate(args) if i not in skip_args]
if len(g) == 1:
return(g[0], fn(*args, **vargs))
else:
return (g, fn(*args, **vargs))
return wrapped
return decorator
|
[
"def",
"zip_with_output",
"(",
"skip_args",
"=",
"[",
"]",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"vargs",
")",
":",
"g",
"=",
"[",
"arg",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
"if",
"i",
"not",
"in",
"skip_args",
"]",
"if",
"len",
"(",
"g",
")",
"==",
"1",
":",
"return",
"(",
"g",
"[",
"0",
"]",
",",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"vargs",
")",
")",
"else",
":",
"return",
"(",
"g",
",",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"vargs",
")",
")",
"return",
"wrapped",
"return",
"decorator"
] |
decorater that zips the input of a function with its output
only zips positional arguments.
skip_args : list
a list of indexes of arguments to exclude from the skip
@zip_with_output(skip_args=[0])
def foo(bar, baz):
return baz
will decorate foo s.t.
foo(x, y) = y
|
[
"decorater",
"that",
"zips",
"the",
"input",
"of",
"a",
"function",
"with",
"its",
"output",
"only",
"zips",
"positional",
"arguments",
"."
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/helpers.py#L29-L52
|
242,578
|
Archived-Object/ligament
|
ligament/helpers.py
|
capture_exception
|
def capture_exception(fn):
"""decorator that catches and returns an exception from wrapped function"""
def wrapped(*args):
try:
return fn(*args)
except Exception as e:
return e
return wrapped
|
python
|
def capture_exception(fn):
"""decorator that catches and returns an exception from wrapped function"""
def wrapped(*args):
try:
return fn(*args)
except Exception as e:
return e
return wrapped
|
[
"def",
"capture_exception",
"(",
"fn",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
")",
":",
"try",
":",
"return",
"fn",
"(",
"*",
"args",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"e",
"return",
"wrapped"
] |
decorator that catches and returns an exception from wrapped function
|
[
"decorator",
"that",
"catches",
"and",
"returns",
"an",
"exception",
"from",
"wrapped",
"function"
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/helpers.py#L55-L62
|
242,579
|
Archived-Object/ligament
|
ligament/helpers.py
|
compose
|
def compose(*funcs):
"""compose a list of functions"""
return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)
|
python
|
def compose(*funcs):
"""compose a list of functions"""
return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)
|
[
"def",
"compose",
"(",
"*",
"funcs",
")",
":",
"return",
"lambda",
"x",
":",
"reduce",
"(",
"lambda",
"v",
",",
"f",
":",
"f",
"(",
"v",
")",
",",
"reversed",
"(",
"funcs",
")",
",",
"x",
")"
] |
compose a list of functions
|
[
"compose",
"a",
"list",
"of",
"functions"
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/helpers.py#L65-L67
|
242,580
|
Archived-Object/ligament
|
ligament/helpers.py
|
map_over_glob
|
def map_over_glob(fn, path, pattern):
"""map a function over a glob pattern, relative to a directory"""
return [fn(x) for x in glob.glob(os.path.join(path, pattern))]
|
python
|
def map_over_glob(fn, path, pattern):
"""map a function over a glob pattern, relative to a directory"""
return [fn(x) for x in glob.glob(os.path.join(path, pattern))]
|
[
"def",
"map_over_glob",
"(",
"fn",
",",
"path",
",",
"pattern",
")",
":",
"return",
"[",
"fn",
"(",
"x",
")",
"for",
"x",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"pattern",
")",
")",
"]"
] |
map a function over a glob pattern, relative to a directory
|
[
"map",
"a",
"function",
"over",
"a",
"glob",
"pattern",
"relative",
"to",
"a",
"directory"
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/helpers.py#L100-L102
|
242,581
|
Archived-Object/ligament
|
ligament/helpers.py
|
mkdir_recursive
|
def mkdir_recursive(dirname):
"""makes all the directories along a given path, if they do not exist"""
parent = os.path.dirname(dirname)
if parent != "":
if not os.path.exists(parent):
mkdir_recursive(parent)
if not os.path.exists(dirname):
os.mkdir(dirname)
elif not os.path.exists(dirname):
os.mkdir(dirname)
|
python
|
def mkdir_recursive(dirname):
"""makes all the directories along a given path, if they do not exist"""
parent = os.path.dirname(dirname)
if parent != "":
if not os.path.exists(parent):
mkdir_recursive(parent)
if not os.path.exists(dirname):
os.mkdir(dirname)
elif not os.path.exists(dirname):
os.mkdir(dirname)
|
[
"def",
"mkdir_recursive",
"(",
"dirname",
")",
":",
"parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"dirname",
")",
"if",
"parent",
"!=",
"\"\"",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"parent",
")",
":",
"mkdir_recursive",
"(",
"parent",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"os",
".",
"mkdir",
"(",
"dirname",
")",
"elif",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"os",
".",
"mkdir",
"(",
"dirname",
")"
] |
makes all the directories along a given path, if they do not exist
|
[
"makes",
"all",
"the",
"directories",
"along",
"a",
"given",
"path",
"if",
"they",
"do",
"not",
"exist"
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/helpers.py#L105-L114
|
242,582
|
Archived-Object/ligament
|
ligament/helpers.py
|
indent_text
|
def indent_text(*strs, **kwargs):
""" indents text according to an operater string and a global indentation
level. returns a tuple of all passed args, indented according to the
operator string
indent: [defaults to +0]
The operator string, of the form
++n : increments the global indentation level by n and indents
+n : indents with the global indentation level + n
--n : decrements the global indentation level by n
-n : indents with the global indentation level - n
==n : sets the global indentation level to exactly n and indents
=n : indents with an indentation level of exactly n
"""
# python 2.7 workaround
indent = kwargs["indent"] if "indent" in kwargs else"+0"
autobreak = kwargs.get("autobreak", False)
char_limit = kwargs.get("char_limit", 80)
split_char = kwargs.get("split_char", " ")
strs = list(strs)
if autobreak:
for index, s in enumerate(strs):
if len(s) > char_limit:
strs[index] = []
spl = s.split(split_char)
result = []
collect = ""
for current_block in spl:
if len(current_block) + len(collect) > char_limit:
strs[index].append(collect[:-1] + "\n")
collect = " "
collect += current_block + split_char
strs[index].append(collect + "\n")
strs = flatten_list(strs)
global lasting_indent
if indent.startswith("++"):
lasting_indent = lasting_indent + int(indent[2:])
cur_indent = lasting_indent
elif indent.startswith("+"):
cur_indent = lasting_indent + int(indent[1:])
elif indent.startswith("--"):
lasting_indent = lasting_indent - int(indent[2:])
cur_indent = lasting_indent
elif indent.startswith("-"):
cur_indent = lasting_indent - int(indent[1:])
elif indent.startswith("=="):
lasting_indent = int(indent[2:])
cur_indent = lasting_indent
elif indent.startswith("="):
lasting_indent = int(indent[1:])
cur_indent = int(indent[1:])
else:
raise Exception(
"indent command format '%s' unrecognized (see the docstring)")
# mutate indentation level if needed
return tuple([" " * cur_indent] + [elem.replace("\n", "\n" + " " * cur_indent)
for elem in strs])
|
python
|
def indent_text(*strs, **kwargs):
""" indents text according to an operater string and a global indentation
level. returns a tuple of all passed args, indented according to the
operator string
indent: [defaults to +0]
The operator string, of the form
++n : increments the global indentation level by n and indents
+n : indents with the global indentation level + n
--n : decrements the global indentation level by n
-n : indents with the global indentation level - n
==n : sets the global indentation level to exactly n and indents
=n : indents with an indentation level of exactly n
"""
# python 2.7 workaround
indent = kwargs["indent"] if "indent" in kwargs else"+0"
autobreak = kwargs.get("autobreak", False)
char_limit = kwargs.get("char_limit", 80)
split_char = kwargs.get("split_char", " ")
strs = list(strs)
if autobreak:
for index, s in enumerate(strs):
if len(s) > char_limit:
strs[index] = []
spl = s.split(split_char)
result = []
collect = ""
for current_block in spl:
if len(current_block) + len(collect) > char_limit:
strs[index].append(collect[:-1] + "\n")
collect = " "
collect += current_block + split_char
strs[index].append(collect + "\n")
strs = flatten_list(strs)
global lasting_indent
if indent.startswith("++"):
lasting_indent = lasting_indent + int(indent[2:])
cur_indent = lasting_indent
elif indent.startswith("+"):
cur_indent = lasting_indent + int(indent[1:])
elif indent.startswith("--"):
lasting_indent = lasting_indent - int(indent[2:])
cur_indent = lasting_indent
elif indent.startswith("-"):
cur_indent = lasting_indent - int(indent[1:])
elif indent.startswith("=="):
lasting_indent = int(indent[2:])
cur_indent = lasting_indent
elif indent.startswith("="):
lasting_indent = int(indent[1:])
cur_indent = int(indent[1:])
else:
raise Exception(
"indent command format '%s' unrecognized (see the docstring)")
# mutate indentation level if needed
return tuple([" " * cur_indent] + [elem.replace("\n", "\n" + " " * cur_indent)
for elem in strs])
|
[
"def",
"indent_text",
"(",
"*",
"strs",
",",
"*",
"*",
"kwargs",
")",
":",
"# python 2.7 workaround",
"indent",
"=",
"kwargs",
"[",
"\"indent\"",
"]",
"if",
"\"indent\"",
"in",
"kwargs",
"else",
"\"+0\"",
"autobreak",
"=",
"kwargs",
".",
"get",
"(",
"\"autobreak\"",
",",
"False",
")",
"char_limit",
"=",
"kwargs",
".",
"get",
"(",
"\"char_limit\"",
",",
"80",
")",
"split_char",
"=",
"kwargs",
".",
"get",
"(",
"\"split_char\"",
",",
"\" \"",
")",
"strs",
"=",
"list",
"(",
"strs",
")",
"if",
"autobreak",
":",
"for",
"index",
",",
"s",
"in",
"enumerate",
"(",
"strs",
")",
":",
"if",
"len",
"(",
"s",
")",
">",
"char_limit",
":",
"strs",
"[",
"index",
"]",
"=",
"[",
"]",
"spl",
"=",
"s",
".",
"split",
"(",
"split_char",
")",
"result",
"=",
"[",
"]",
"collect",
"=",
"\"\"",
"for",
"current_block",
"in",
"spl",
":",
"if",
"len",
"(",
"current_block",
")",
"+",
"len",
"(",
"collect",
")",
">",
"char_limit",
":",
"strs",
"[",
"index",
"]",
".",
"append",
"(",
"collect",
"[",
":",
"-",
"1",
"]",
"+",
"\"\\n\"",
")",
"collect",
"=",
"\" \"",
"collect",
"+=",
"current_block",
"+",
"split_char",
"strs",
"[",
"index",
"]",
".",
"append",
"(",
"collect",
"+",
"\"\\n\"",
")",
"strs",
"=",
"flatten_list",
"(",
"strs",
")",
"global",
"lasting_indent",
"if",
"indent",
".",
"startswith",
"(",
"\"++\"",
")",
":",
"lasting_indent",
"=",
"lasting_indent",
"+",
"int",
"(",
"indent",
"[",
"2",
":",
"]",
")",
"cur_indent",
"=",
"lasting_indent",
"elif",
"indent",
".",
"startswith",
"(",
"\"+\"",
")",
":",
"cur_indent",
"=",
"lasting_indent",
"+",
"int",
"(",
"indent",
"[",
"1",
":",
"]",
")",
"elif",
"indent",
".",
"startswith",
"(",
"\"--\"",
")",
":",
"lasting_indent",
"=",
"lasting_indent",
"-",
"int",
"(",
"indent",
"[",
"2",
":",
"]",
")",
"cur_indent",
"=",
"lasting_indent",
"elif",
"indent",
".",
"startswith",
"(",
"\"-\"",
")",
":",
"cur_indent",
"=",
"lasting_indent",
"-",
"int",
"(",
"indent",
"[",
"1",
":",
"]",
")",
"elif",
"indent",
".",
"startswith",
"(",
"\"==\"",
")",
":",
"lasting_indent",
"=",
"int",
"(",
"indent",
"[",
"2",
":",
"]",
")",
"cur_indent",
"=",
"lasting_indent",
"elif",
"indent",
".",
"startswith",
"(",
"\"=\"",
")",
":",
"lasting_indent",
"=",
"int",
"(",
"indent",
"[",
"1",
":",
"]",
")",
"cur_indent",
"=",
"int",
"(",
"indent",
"[",
"1",
":",
"]",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"indent command format '%s' unrecognized (see the docstring)\"",
")",
"# mutate indentation level if needed",
"return",
"tuple",
"(",
"[",
"\" \"",
"*",
"cur_indent",
"]",
"+",
"[",
"elem",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\\n\"",
"+",
"\" \"",
"*",
"cur_indent",
")",
"for",
"elem",
"in",
"strs",
"]",
")"
] |
indents text according to an operater string and a global indentation
level. returns a tuple of all passed args, indented according to the
operator string
indent: [defaults to +0]
The operator string, of the form
++n : increments the global indentation level by n and indents
+n : indents with the global indentation level + n
--n : decrements the global indentation level by n
-n : indents with the global indentation level - n
==n : sets the global indentation level to exactly n and indents
=n : indents with an indentation level of exactly n
|
[
"indents",
"text",
"according",
"to",
"an",
"operater",
"string",
"and",
"a",
"global",
"indentation",
"level",
".",
"returns",
"a",
"tuple",
"of",
"all",
"passed",
"args",
"indented",
"according",
"to",
"the",
"operator",
"string"
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/helpers.py#L142-L203
|
242,583
|
Archived-Object/ligament
|
ligament/helpers.py
|
pdebug
|
def pdebug(*args, **kwargs):
"""print formatted output to stdout with indentation control"""
if should_msg(kwargs.get("groups", ["debug"])):
# initialize colorama only if uninitialized
global colorama_init
if not colorama_init:
colorama_init = True
colorama.init()
args = indent_text(*args, **kwargs)
# write to stdout
sys.stderr.write(colorama.Fore.CYAN)
sys.stderr.write("".join(args))
sys.stderr.write(colorama.Fore.RESET)
sys.stderr.write("\n")
|
python
|
def pdebug(*args, **kwargs):
"""print formatted output to stdout with indentation control"""
if should_msg(kwargs.get("groups", ["debug"])):
# initialize colorama only if uninitialized
global colorama_init
if not colorama_init:
colorama_init = True
colorama.init()
args = indent_text(*args, **kwargs)
# write to stdout
sys.stderr.write(colorama.Fore.CYAN)
sys.stderr.write("".join(args))
sys.stderr.write(colorama.Fore.RESET)
sys.stderr.write("\n")
|
[
"def",
"pdebug",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"should_msg",
"(",
"kwargs",
".",
"get",
"(",
"\"groups\"",
",",
"[",
"\"debug\"",
"]",
")",
")",
":",
"# initialize colorama only if uninitialized",
"global",
"colorama_init",
"if",
"not",
"colorama_init",
":",
"colorama_init",
"=",
"True",
"colorama",
".",
"init",
"(",
")",
"args",
"=",
"indent_text",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# write to stdout",
"sys",
".",
"stderr",
".",
"write",
"(",
"colorama",
".",
"Fore",
".",
"CYAN",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\"",
".",
"join",
"(",
"args",
")",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"colorama",
".",
"Fore",
".",
"RESET",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\n\"",
")"
] |
print formatted output to stdout with indentation control
|
[
"print",
"formatted",
"output",
"to",
"stdout",
"with",
"indentation",
"control"
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/helpers.py#L247-L262
|
242,584
|
Archived-Object/ligament
|
ligament/helpers.py
|
pout
|
def pout(*args, **kwargs):
"""print to stdout, maintaining indent level"""
if should_msg(kwargs.get("groups", ["normal"])):
args = indent_text(*args, **kwargs)
# write to stdout
sys.stderr.write("".join(args))
sys.stderr.write("\n")
|
python
|
def pout(*args, **kwargs):
"""print to stdout, maintaining indent level"""
if should_msg(kwargs.get("groups", ["normal"])):
args = indent_text(*args, **kwargs)
# write to stdout
sys.stderr.write("".join(args))
sys.stderr.write("\n")
|
[
"def",
"pout",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"should_msg",
"(",
"kwargs",
".",
"get",
"(",
"\"groups\"",
",",
"[",
"\"normal\"",
"]",
")",
")",
":",
"args",
"=",
"indent_text",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# write to stdout",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\"",
".",
"join",
"(",
"args",
")",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"\\n\"",
")"
] |
print to stdout, maintaining indent level
|
[
"print",
"to",
"stdout",
"maintaining",
"indent",
"level"
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/helpers.py#L265-L272
|
242,585
|
Archived-Object/ligament
|
ligament/helpers.py
|
urlretrieve
|
def urlretrieve(url, dest, write_mode="w"):
"""save a file to disk from a given url"""
response = urllib2.urlopen(url)
mkdir_recursive(os.path.dirname(dest))
with open(dest, write_mode) as f:
f.write(response.read())
f.close()
|
python
|
def urlretrieve(url, dest, write_mode="w"):
"""save a file to disk from a given url"""
response = urllib2.urlopen(url)
mkdir_recursive(os.path.dirname(dest))
with open(dest, write_mode) as f:
f.write(response.read())
f.close()
|
[
"def",
"urlretrieve",
"(",
"url",
",",
"dest",
",",
"write_mode",
"=",
"\"w\"",
")",
":",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
")",
"mkdir_recursive",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"dest",
")",
")",
"with",
"open",
"(",
"dest",
",",
"write_mode",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"response",
".",
"read",
"(",
")",
")",
"f",
".",
"close",
"(",
")"
] |
save a file to disk from a given url
|
[
"save",
"a",
"file",
"to",
"disk",
"from",
"a",
"given",
"url"
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/helpers.py#L275-L281
|
242,586
|
Archived-Object/ligament
|
ligament/helpers.py
|
remove_dups
|
def remove_dups(seq):
"""remove duplicates from a sequence, preserving order"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
python
|
def remove_dups(seq):
"""remove duplicates from a sequence, preserving order"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
[
"def",
"remove_dups",
"(",
"seq",
")",
":",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"return",
"[",
"x",
"for",
"x",
"in",
"seq",
"if",
"not",
"(",
"x",
"in",
"seen",
"or",
"seen_add",
"(",
"x",
")",
")",
"]"
] |
remove duplicates from a sequence, preserving order
|
[
"remove",
"duplicates",
"from",
"a",
"sequence",
"preserving",
"order"
] |
ff3d78130522676a20dc64086dc8a27b197cc20f
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament/helpers.py#L291-L295
|
242,587
|
rehandalal/buchner
|
buchner/helpers.py
|
json_requested
|
def json_requested():
"""Check if json is the preferred output format for the request."""
best = request.accept_mimetypes.best_match(
['application/json', 'text/html'])
return (best == 'application/json' and
request.accept_mimetypes[best] >
request.accept_mimetypes['text/html'])
|
python
|
def json_requested():
"""Check if json is the preferred output format for the request."""
best = request.accept_mimetypes.best_match(
['application/json', 'text/html'])
return (best == 'application/json' and
request.accept_mimetypes[best] >
request.accept_mimetypes['text/html'])
|
[
"def",
"json_requested",
"(",
")",
":",
"best",
"=",
"request",
".",
"accept_mimetypes",
".",
"best_match",
"(",
"[",
"'application/json'",
",",
"'text/html'",
"]",
")",
"return",
"(",
"best",
"==",
"'application/json'",
"and",
"request",
".",
"accept_mimetypes",
"[",
"best",
"]",
">",
"request",
".",
"accept_mimetypes",
"[",
"'text/html'",
"]",
")"
] |
Check if json is the preferred output format for the request.
|
[
"Check",
"if",
"json",
"is",
"the",
"preferred",
"output",
"format",
"for",
"the",
"request",
"."
] |
dc22a61c493b9d4a74d76e8b42a319aa13e385f3
|
https://github.com/rehandalal/buchner/blob/dc22a61c493b9d4a74d76e8b42a319aa13e385f3/buchner/helpers.py#L13-L19
|
242,588
|
emin63/eyap
|
setup.py
|
get_readme
|
def get_readme():
'Get the long description from the README file'
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as my_fd:
result = my_fd.read()
return result
|
python
|
def get_readme():
'Get the long description from the README file'
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as my_fd:
result = my_fd.read()
return result
|
[
"def",
"get_readme",
"(",
")",
":",
"here",
"=",
"path",
".",
"abspath",
"(",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"here",
",",
"'README.rst'",
")",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"my_fd",
":",
"result",
"=",
"my_fd",
".",
"read",
"(",
")",
"return",
"result"
] |
Get the long description from the README file
|
[
"Get",
"the",
"long",
"description",
"from",
"the",
"README",
"file"
] |
a610761973b478ca0e864e970be05ce29d5994a5
|
https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/setup.py#L14-L21
|
242,589
|
pacificclimate/cfmeta
|
cfmeta/cmipfile.py
|
get_nc_attrs
|
def get_nc_attrs(nc):
"""Gets netCDF file metadata attributes.
Arguments:
nc (netCDF4.Dataset): an open NetCDF4 Dataset to pull attributes from.
Returns:
dict: Metadata as extracted from the netCDF file.
"""
meta = {
'experiment': nc.experiment_id,
'frequency': nc.frequency,
'institute': nc.institute_id,
'model': nc.model_id,
'modeling_realm': nc.modeling_realm,
'ensemble_member': 'r{}i{}p{}'.format(nc.realization, nc.initialization_method, nc.physics_version),
}
variable_name = get_var_name(nc)
if variable_name:
meta.update({'variable_name': variable_name})
return meta
|
python
|
def get_nc_attrs(nc):
"""Gets netCDF file metadata attributes.
Arguments:
nc (netCDF4.Dataset): an open NetCDF4 Dataset to pull attributes from.
Returns:
dict: Metadata as extracted from the netCDF file.
"""
meta = {
'experiment': nc.experiment_id,
'frequency': nc.frequency,
'institute': nc.institute_id,
'model': nc.model_id,
'modeling_realm': nc.modeling_realm,
'ensemble_member': 'r{}i{}p{}'.format(nc.realization, nc.initialization_method, nc.physics_version),
}
variable_name = get_var_name(nc)
if variable_name:
meta.update({'variable_name': variable_name})
return meta
|
[
"def",
"get_nc_attrs",
"(",
"nc",
")",
":",
"meta",
"=",
"{",
"'experiment'",
":",
"nc",
".",
"experiment_id",
",",
"'frequency'",
":",
"nc",
".",
"frequency",
",",
"'institute'",
":",
"nc",
".",
"institute_id",
",",
"'model'",
":",
"nc",
".",
"model_id",
",",
"'modeling_realm'",
":",
"nc",
".",
"modeling_realm",
",",
"'ensemble_member'",
":",
"'r{}i{}p{}'",
".",
"format",
"(",
"nc",
".",
"realization",
",",
"nc",
".",
"initialization_method",
",",
"nc",
".",
"physics_version",
")",
",",
"}",
"variable_name",
"=",
"get_var_name",
"(",
"nc",
")",
"if",
"variable_name",
":",
"meta",
".",
"update",
"(",
"{",
"'variable_name'",
":",
"variable_name",
"}",
")",
"return",
"meta"
] |
Gets netCDF file metadata attributes.
Arguments:
nc (netCDF4.Dataset): an open NetCDF4 Dataset to pull attributes from.
Returns:
dict: Metadata as extracted from the netCDF file.
|
[
"Gets",
"netCDF",
"file",
"metadata",
"attributes",
"."
] |
a6eef78d0bce523bb44920ba96233f034b60316a
|
https://github.com/pacificclimate/cfmeta/blob/a6eef78d0bce523bb44920ba96233f034b60316a/cfmeta/cmipfile.py#L151-L174
|
242,590
|
pacificclimate/cfmeta
|
cfmeta/cmipfile.py
|
get_var_name
|
def get_var_name(nc):
"""Guesses the variable_name of an open NetCDF file
"""
non_variable_names = [
'lat',
'lat_bnds',
'lon',
'lon_bnds',
'time',
'latitude',
'longitude',
'bnds'
]
_vars = set(nc.variables.keys())
_vars.difference_update(set(non_variable_names))
if len(_vars) == 1:
return _vars.pop()
return None
|
python
|
def get_var_name(nc):
"""Guesses the variable_name of an open NetCDF file
"""
non_variable_names = [
'lat',
'lat_bnds',
'lon',
'lon_bnds',
'time',
'latitude',
'longitude',
'bnds'
]
_vars = set(nc.variables.keys())
_vars.difference_update(set(non_variable_names))
if len(_vars) == 1:
return _vars.pop()
return None
|
[
"def",
"get_var_name",
"(",
"nc",
")",
":",
"non_variable_names",
"=",
"[",
"'lat'",
",",
"'lat_bnds'",
",",
"'lon'",
",",
"'lon_bnds'",
",",
"'time'",
",",
"'latitude'",
",",
"'longitude'",
",",
"'bnds'",
"]",
"_vars",
"=",
"set",
"(",
"nc",
".",
"variables",
".",
"keys",
"(",
")",
")",
"_vars",
".",
"difference_update",
"(",
"set",
"(",
"non_variable_names",
")",
")",
"if",
"len",
"(",
"_vars",
")",
"==",
"1",
":",
"return",
"_vars",
".",
"pop",
"(",
")",
"return",
"None"
] |
Guesses the variable_name of an open NetCDF file
|
[
"Guesses",
"the",
"variable_name",
"of",
"an",
"open",
"NetCDF",
"file"
] |
a6eef78d0bce523bb44920ba96233f034b60316a
|
https://github.com/pacificclimate/cfmeta/blob/a6eef78d0bce523bb44920ba96233f034b60316a/cfmeta/cmipfile.py#L176-L195
|
242,591
|
pacificclimate/cfmeta
|
cfmeta/cmipfile.py
|
CmipFile._update_known_atts
|
def _update_known_atts(self, **kwargs):
"""Updates instance attributes with supplied keyword arguments.
"""
for k, v in kwargs.items():
if k not in ATTR_KEYS:
# Warn if passed in unknown kwargs
raise SyntaxWarning('Unknown argument: {}'.format(k))
elif not v: # Delete attributes with falsey values
delattr(self, k)
else:
setattr(self, k, v)
|
python
|
def _update_known_atts(self, **kwargs):
"""Updates instance attributes with supplied keyword arguments.
"""
for k, v in kwargs.items():
if k not in ATTR_KEYS:
# Warn if passed in unknown kwargs
raise SyntaxWarning('Unknown argument: {}'.format(k))
elif not v: # Delete attributes with falsey values
delattr(self, k)
else:
setattr(self, k, v)
|
[
"def",
"_update_known_atts",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"ATTR_KEYS",
":",
"# Warn if passed in unknown kwargs",
"raise",
"SyntaxWarning",
"(",
"'Unknown argument: {}'",
".",
"format",
"(",
"k",
")",
")",
"elif",
"not",
"v",
":",
"# Delete attributes with falsey values",
"delattr",
"(",
"self",
",",
"k",
")",
"else",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")"
] |
Updates instance attributes with supplied keyword arguments.
|
[
"Updates",
"instance",
"attributes",
"with",
"supplied",
"keyword",
"arguments",
"."
] |
a6eef78d0bce523bb44920ba96233f034b60316a
|
https://github.com/pacificclimate/cfmeta/blob/a6eef78d0bce523bb44920ba96233f034b60316a/cfmeta/cmipfile.py#L57-L67
|
242,592
|
redbridge/molnctrl
|
molnctrl/cachemaker.py
|
savecache
|
def savecache(apicache, json_file):
"""
Saves apicache dictionary as json_file, returns dictionary as indented str
"""
if apicache is None or apicache is {}:
return ""
apicachestr = json.dumps(apicache, indent=2)
with open(json_file, 'w') as cache_file:
cache_file.write(apicachestr)
return apicachestr
|
python
|
def savecache(apicache, json_file):
"""
Saves apicache dictionary as json_file, returns dictionary as indented str
"""
if apicache is None or apicache is {}:
return ""
apicachestr = json.dumps(apicache, indent=2)
with open(json_file, 'w') as cache_file:
cache_file.write(apicachestr)
return apicachestr
|
[
"def",
"savecache",
"(",
"apicache",
",",
"json_file",
")",
":",
"if",
"apicache",
"is",
"None",
"or",
"apicache",
"is",
"{",
"}",
":",
"return",
"\"\"",
"apicachestr",
"=",
"json",
".",
"dumps",
"(",
"apicache",
",",
"indent",
"=",
"2",
")",
"with",
"open",
"(",
"json_file",
",",
"'w'",
")",
"as",
"cache_file",
":",
"cache_file",
".",
"write",
"(",
"apicachestr",
")",
"return",
"apicachestr"
] |
Saves apicache dictionary as json_file, returns dictionary as indented str
|
[
"Saves",
"apicache",
"dictionary",
"as",
"json_file",
"returns",
"dictionary",
"as",
"indented",
"str"
] |
9990ae7e522ce364bb61a735f774dc28de5f8e60
|
https://github.com/redbridge/molnctrl/blob/9990ae7e522ce364bb61a735f774dc28de5f8e60/molnctrl/cachemaker.py#L55-L64
|
242,593
|
redbridge/molnctrl
|
molnctrl/cachemaker.py
|
loadcache
|
def loadcache(json_file):
"""
Loads json file as dictionary, feeds it to monkeycache and spits result
"""
f = open(json_file, 'r')
data = f.read()
f.close()
try:
apicache = json.loads(data)
except ValueError as e:
print("Error processing json:", json_file, e)
return {}
return apicache
|
python
|
def loadcache(json_file):
"""
Loads json file as dictionary, feeds it to monkeycache and spits result
"""
f = open(json_file, 'r')
data = f.read()
f.close()
try:
apicache = json.loads(data)
except ValueError as e:
print("Error processing json:", json_file, e)
return {}
return apicache
|
[
"def",
"loadcache",
"(",
"json_file",
")",
":",
"f",
"=",
"open",
"(",
"json_file",
",",
"'r'",
")",
"data",
"=",
"f",
".",
"read",
"(",
")",
"f",
".",
"close",
"(",
")",
"try",
":",
"apicache",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"except",
"ValueError",
"as",
"e",
":",
"print",
"(",
"\"Error processing json:\"",
",",
"json_file",
",",
"e",
")",
"return",
"{",
"}",
"return",
"apicache"
] |
Loads json file as dictionary, feeds it to monkeycache and spits result
|
[
"Loads",
"json",
"file",
"as",
"dictionary",
"feeds",
"it",
"to",
"monkeycache",
"and",
"spits",
"result"
] |
9990ae7e522ce364bb61a735f774dc28de5f8e60
|
https://github.com/redbridge/molnctrl/blob/9990ae7e522ce364bb61a735f774dc28de5f8e60/molnctrl/cachemaker.py#L67-L79
|
242,594
|
redbridge/molnctrl
|
molnctrl/cachemaker.py
|
monkeycache
|
def monkeycache(apis):
"""
Feed this a dictionary of api bananas, it spits out processed cache
"""
if isinstance(type(apis), type(None)) or apis is None:
return {}
verbs = set()
cache = {}
cache['count'] = apis['count']
cache['asyncapis'] = []
apilist = apis['api']
if apilist is None:
print("[monkeycache] Server response issue, no apis found")
for api in apilist:
name = getvalue(api, 'name')
verb, subject = splitverbsubject(name)
apidict = {}
apidict['name'] = name
apidict['description'] = getvalue(api, 'description')
apidict['isasync'] = getvalue(api, 'isasync')
if apidict['isasync']:
cache['asyncapis'].append(name)
apidict['related'] = splitcsvstring(getvalue(api, 'related'))
required = []
apiparams = []
for param in getvalue(api, 'params'):
apiparam = {}
apiparam['name'] = getvalue(param, 'name')
apiparam['description'] = getvalue(param, 'description')
apiparam['required'] = (getvalue(param, 'required') is True)
apiparam['length'] = int(getvalue(param, 'length'))
apiparam['type'] = getvalue(param, 'type')
apiparam['related'] = splitcsvstring(getvalue(param, 'related'))
if apiparam['required']:
required.append(apiparam['name'])
apiparams.append(apiparam)
apidict['requiredparams'] = required
apidict['params'] = apiparams
if verb not in cache:
cache[verb] = {}
cache[verb][subject] = apidict
verbs.add(verb)
cache['verbs'] = list(verbs)
return cache
|
python
|
def monkeycache(apis):
"""
Feed this a dictionary of api bananas, it spits out processed cache
"""
if isinstance(type(apis), type(None)) or apis is None:
return {}
verbs = set()
cache = {}
cache['count'] = apis['count']
cache['asyncapis'] = []
apilist = apis['api']
if apilist is None:
print("[monkeycache] Server response issue, no apis found")
for api in apilist:
name = getvalue(api, 'name')
verb, subject = splitverbsubject(name)
apidict = {}
apidict['name'] = name
apidict['description'] = getvalue(api, 'description')
apidict['isasync'] = getvalue(api, 'isasync')
if apidict['isasync']:
cache['asyncapis'].append(name)
apidict['related'] = splitcsvstring(getvalue(api, 'related'))
required = []
apiparams = []
for param in getvalue(api, 'params'):
apiparam = {}
apiparam['name'] = getvalue(param, 'name')
apiparam['description'] = getvalue(param, 'description')
apiparam['required'] = (getvalue(param, 'required') is True)
apiparam['length'] = int(getvalue(param, 'length'))
apiparam['type'] = getvalue(param, 'type')
apiparam['related'] = splitcsvstring(getvalue(param, 'related'))
if apiparam['required']:
required.append(apiparam['name'])
apiparams.append(apiparam)
apidict['requiredparams'] = required
apidict['params'] = apiparams
if verb not in cache:
cache[verb] = {}
cache[verb][subject] = apidict
verbs.add(verb)
cache['verbs'] = list(verbs)
return cache
|
[
"def",
"monkeycache",
"(",
"apis",
")",
":",
"if",
"isinstance",
"(",
"type",
"(",
"apis",
")",
",",
"type",
"(",
"None",
")",
")",
"or",
"apis",
"is",
"None",
":",
"return",
"{",
"}",
"verbs",
"=",
"set",
"(",
")",
"cache",
"=",
"{",
"}",
"cache",
"[",
"'count'",
"]",
"=",
"apis",
"[",
"'count'",
"]",
"cache",
"[",
"'asyncapis'",
"]",
"=",
"[",
"]",
"apilist",
"=",
"apis",
"[",
"'api'",
"]",
"if",
"apilist",
"is",
"None",
":",
"print",
"(",
"\"[monkeycache] Server response issue, no apis found\"",
")",
"for",
"api",
"in",
"apilist",
":",
"name",
"=",
"getvalue",
"(",
"api",
",",
"'name'",
")",
"verb",
",",
"subject",
"=",
"splitverbsubject",
"(",
"name",
")",
"apidict",
"=",
"{",
"}",
"apidict",
"[",
"'name'",
"]",
"=",
"name",
"apidict",
"[",
"'description'",
"]",
"=",
"getvalue",
"(",
"api",
",",
"'description'",
")",
"apidict",
"[",
"'isasync'",
"]",
"=",
"getvalue",
"(",
"api",
",",
"'isasync'",
")",
"if",
"apidict",
"[",
"'isasync'",
"]",
":",
"cache",
"[",
"'asyncapis'",
"]",
".",
"append",
"(",
"name",
")",
"apidict",
"[",
"'related'",
"]",
"=",
"splitcsvstring",
"(",
"getvalue",
"(",
"api",
",",
"'related'",
")",
")",
"required",
"=",
"[",
"]",
"apiparams",
"=",
"[",
"]",
"for",
"param",
"in",
"getvalue",
"(",
"api",
",",
"'params'",
")",
":",
"apiparam",
"=",
"{",
"}",
"apiparam",
"[",
"'name'",
"]",
"=",
"getvalue",
"(",
"param",
",",
"'name'",
")",
"apiparam",
"[",
"'description'",
"]",
"=",
"getvalue",
"(",
"param",
",",
"'description'",
")",
"apiparam",
"[",
"'required'",
"]",
"=",
"(",
"getvalue",
"(",
"param",
",",
"'required'",
")",
"is",
"True",
")",
"apiparam",
"[",
"'length'",
"]",
"=",
"int",
"(",
"getvalue",
"(",
"param",
",",
"'length'",
")",
")",
"apiparam",
"[",
"'type'",
"]",
"=",
"getvalue",
"(",
"param",
",",
"'type'",
")",
"apiparam",
"[",
"'related'",
"]",
"=",
"splitcsvstring",
"(",
"getvalue",
"(",
"param",
",",
"'related'",
")",
")",
"if",
"apiparam",
"[",
"'required'",
"]",
":",
"required",
".",
"append",
"(",
"apiparam",
"[",
"'name'",
"]",
")",
"apiparams",
".",
"append",
"(",
"apiparam",
")",
"apidict",
"[",
"'requiredparams'",
"]",
"=",
"required",
"apidict",
"[",
"'params'",
"]",
"=",
"apiparams",
"if",
"verb",
"not",
"in",
"cache",
":",
"cache",
"[",
"verb",
"]",
"=",
"{",
"}",
"cache",
"[",
"verb",
"]",
"[",
"subject",
"]",
"=",
"apidict",
"verbs",
".",
"add",
"(",
"verb",
")",
"cache",
"[",
"'verbs'",
"]",
"=",
"list",
"(",
"verbs",
")",
"return",
"cache"
] |
Feed this a dictionary of api bananas, it spits out processed cache
|
[
"Feed",
"this",
"a",
"dictionary",
"of",
"api",
"bananas",
"it",
"spits",
"out",
"processed",
"cache"
] |
9990ae7e522ce364bb61a735f774dc28de5f8e60
|
https://github.com/redbridge/molnctrl/blob/9990ae7e522ce364bb61a735f774dc28de5f8e60/molnctrl/cachemaker.py#L82-L132
|
242,595
|
zagfai/webtul
|
webtul/db.py
|
MySQL.execute
|
def execute(self, sql, param=(), times=1):
"""This function is the most use one, with the paramter times
it will try x times to execute the sql, default is 1.
"""
self.log and self.log.debug('%s %s' % ('SQL:', sql))
if param is not ():
self.log and self.log.debug('%s %s' % ('PARAMs:', param))
for i in xrange(times):
try:
ret, res = self._execute(sql, param)
return ret, res
except Exception, e:
self.log and self.log.warn("The %s time execute, fail" % i)
self.log and self.log.warn(e)
if i: sleep(i**1.5)
self.log and self.log.error(e)
return None, e
|
python
|
def execute(self, sql, param=(), times=1):
"""This function is the most use one, with the paramter times
it will try x times to execute the sql, default is 1.
"""
self.log and self.log.debug('%s %s' % ('SQL:', sql))
if param is not ():
self.log and self.log.debug('%s %s' % ('PARAMs:', param))
for i in xrange(times):
try:
ret, res = self._execute(sql, param)
return ret, res
except Exception, e:
self.log and self.log.warn("The %s time execute, fail" % i)
self.log and self.log.warn(e)
if i: sleep(i**1.5)
self.log and self.log.error(e)
return None, e
|
[
"def",
"execute",
"(",
"self",
",",
"sql",
",",
"param",
"=",
"(",
")",
",",
"times",
"=",
"1",
")",
":",
"self",
".",
"log",
"and",
"self",
".",
"log",
".",
"debug",
"(",
"'%s %s'",
"%",
"(",
"'SQL:'",
",",
"sql",
")",
")",
"if",
"param",
"is",
"not",
"(",
")",
":",
"self",
".",
"log",
"and",
"self",
".",
"log",
".",
"debug",
"(",
"'%s %s'",
"%",
"(",
"'PARAMs:'",
",",
"param",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"times",
")",
":",
"try",
":",
"ret",
",",
"res",
"=",
"self",
".",
"_execute",
"(",
"sql",
",",
"param",
")",
"return",
"ret",
",",
"res",
"except",
"Exception",
",",
"e",
":",
"self",
".",
"log",
"and",
"self",
".",
"log",
".",
"warn",
"(",
"\"The %s time execute, fail\"",
"%",
"i",
")",
"self",
".",
"log",
"and",
"self",
".",
"log",
".",
"warn",
"(",
"e",
")",
"if",
"i",
":",
"sleep",
"(",
"i",
"**",
"1.5",
")",
"self",
".",
"log",
"and",
"self",
".",
"log",
".",
"error",
"(",
"e",
")",
"return",
"None",
",",
"e"
] |
This function is the most use one, with the paramter times
it will try x times to execute the sql, default is 1.
|
[
"This",
"function",
"is",
"the",
"most",
"use",
"one",
"with",
"the",
"paramter",
"times",
"it",
"will",
"try",
"x",
"times",
"to",
"execute",
"the",
"sql",
"default",
"is",
"1",
"."
] |
58c49928070b56ef54a45b4af20d800b269ad8ce
|
https://github.com/zagfai/webtul/blob/58c49928070b56ef54a45b4af20d800b269ad8ce/webtul/db.py#L50-L66
|
242,596
|
boisgera/about
|
about/__init__.py
|
get_metadata
|
def get_metadata(source):
"""
Extract the metadata from the module or dict argument.
It returns a `metadata` dictionary that provides keywords arguments
for the setuptools `setup` function.
"""
if isinstance(source, types.ModuleType):
metadata = source.__dict__
else:
metadata = source
setuptools_kwargs = {}
for key in "name version url license".split():
val = metadata.get("__" + key + "__")
if val is not None:
setuptools_kwargs[key] = val
version = metadata.get("__version__")
if version is not None:
setuptools_kwargs["version"] = version
# Search for author email with a <...@...> syntax in the author field.
author = metadata.get("__author__")
if author is not None:
email_pattern = u"<([^>]+@[^>]+)>"
match = re.search(email_pattern, author)
if match is not None:
setuptools_kwargs["author_email"] = email = match.groups()[0]
setuptools_kwargs["author"] = author.replace(u"<" + email + u">", u"").strip()
else:
setuptools_kwargs["author"] = author
# Get the module summary.
summary = metadata.get("__summary__")
if summary is not None:
setuptools_kwargs["description"] = summary
# Get and process the module README.
README_filenames = ["README.md", "README.txt", "README"]
for filename in README_filenames:
if os.path.isfile(filename):
README = open(filename).read()
if hasattr(README, "decode"):
README = README.decode("utf-8")
README_rst = to_rst(README)
setuptools_kwargs["long_description"] = README_rst or README
break
# Process keywords that match trove classifiers.
keywords = metadata.get("__keywords__")
if keywords is not None:
classifiers = []
keywords = [k.strip() for k in keywords.split(",")]
for keyword in keywords:
trove_id = trove_search(keyword)
if trove_id is not None:
classifiers.append(trove_id)
classifiers = sorted(list(set(classifiers)))
setuptools_kwargs["classifiers"] = classifiers
return setuptools_kwargs
|
python
|
def get_metadata(source):
"""
Extract the metadata from the module or dict argument.
It returns a `metadata` dictionary that provides keywords arguments
for the setuptools `setup` function.
"""
if isinstance(source, types.ModuleType):
metadata = source.__dict__
else:
metadata = source
setuptools_kwargs = {}
for key in "name version url license".split():
val = metadata.get("__" + key + "__")
if val is not None:
setuptools_kwargs[key] = val
version = metadata.get("__version__")
if version is not None:
setuptools_kwargs["version"] = version
# Search for author email with a <...@...> syntax in the author field.
author = metadata.get("__author__")
if author is not None:
email_pattern = u"<([^>]+@[^>]+)>"
match = re.search(email_pattern, author)
if match is not None:
setuptools_kwargs["author_email"] = email = match.groups()[0]
setuptools_kwargs["author"] = author.replace(u"<" + email + u">", u"").strip()
else:
setuptools_kwargs["author"] = author
# Get the module summary.
summary = metadata.get("__summary__")
if summary is not None:
setuptools_kwargs["description"] = summary
# Get and process the module README.
README_filenames = ["README.md", "README.txt", "README"]
for filename in README_filenames:
if os.path.isfile(filename):
README = open(filename).read()
if hasattr(README, "decode"):
README = README.decode("utf-8")
README_rst = to_rst(README)
setuptools_kwargs["long_description"] = README_rst or README
break
# Process keywords that match trove classifiers.
keywords = metadata.get("__keywords__")
if keywords is not None:
classifiers = []
keywords = [k.strip() for k in keywords.split(",")]
for keyword in keywords:
trove_id = trove_search(keyword)
if trove_id is not None:
classifiers.append(trove_id)
classifiers = sorted(list(set(classifiers)))
setuptools_kwargs["classifiers"] = classifiers
return setuptools_kwargs
|
[
"def",
"get_metadata",
"(",
"source",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"types",
".",
"ModuleType",
")",
":",
"metadata",
"=",
"source",
".",
"__dict__",
"else",
":",
"metadata",
"=",
"source",
"setuptools_kwargs",
"=",
"{",
"}",
"for",
"key",
"in",
"\"name version url license\"",
".",
"split",
"(",
")",
":",
"val",
"=",
"metadata",
".",
"get",
"(",
"\"__\"",
"+",
"key",
"+",
"\"__\"",
")",
"if",
"val",
"is",
"not",
"None",
":",
"setuptools_kwargs",
"[",
"key",
"]",
"=",
"val",
"version",
"=",
"metadata",
".",
"get",
"(",
"\"__version__\"",
")",
"if",
"version",
"is",
"not",
"None",
":",
"setuptools_kwargs",
"[",
"\"version\"",
"]",
"=",
"version",
"# Search for author email with a <...@...> syntax in the author field.",
"author",
"=",
"metadata",
".",
"get",
"(",
"\"__author__\"",
")",
"if",
"author",
"is",
"not",
"None",
":",
"email_pattern",
"=",
"u\"<([^>]+@[^>]+)>\"",
"match",
"=",
"re",
".",
"search",
"(",
"email_pattern",
",",
"author",
")",
"if",
"match",
"is",
"not",
"None",
":",
"setuptools_kwargs",
"[",
"\"author_email\"",
"]",
"=",
"email",
"=",
"match",
".",
"groups",
"(",
")",
"[",
"0",
"]",
"setuptools_kwargs",
"[",
"\"author\"",
"]",
"=",
"author",
".",
"replace",
"(",
"u\"<\"",
"+",
"email",
"+",
"u\">\"",
",",
"u\"\"",
")",
".",
"strip",
"(",
")",
"else",
":",
"setuptools_kwargs",
"[",
"\"author\"",
"]",
"=",
"author",
"# Get the module summary.",
"summary",
"=",
"metadata",
".",
"get",
"(",
"\"__summary__\"",
")",
"if",
"summary",
"is",
"not",
"None",
":",
"setuptools_kwargs",
"[",
"\"description\"",
"]",
"=",
"summary",
"# Get and process the module README.",
"README_filenames",
"=",
"[",
"\"README.md\"",
",",
"\"README.txt\"",
",",
"\"README\"",
"]",
"for",
"filename",
"in",
"README_filenames",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"README",
"=",
"open",
"(",
"filename",
")",
".",
"read",
"(",
")",
"if",
"hasattr",
"(",
"README",
",",
"\"decode\"",
")",
":",
"README",
"=",
"README",
".",
"decode",
"(",
"\"utf-8\"",
")",
"README_rst",
"=",
"to_rst",
"(",
"README",
")",
"setuptools_kwargs",
"[",
"\"long_description\"",
"]",
"=",
"README_rst",
"or",
"README",
"break",
"# Process keywords that match trove classifiers.",
"keywords",
"=",
"metadata",
".",
"get",
"(",
"\"__keywords__\"",
")",
"if",
"keywords",
"is",
"not",
"None",
":",
"classifiers",
"=",
"[",
"]",
"keywords",
"=",
"[",
"k",
".",
"strip",
"(",
")",
"for",
"k",
"in",
"keywords",
".",
"split",
"(",
"\",\"",
")",
"]",
"for",
"keyword",
"in",
"keywords",
":",
"trove_id",
"=",
"trove_search",
"(",
"keyword",
")",
"if",
"trove_id",
"is",
"not",
"None",
":",
"classifiers",
".",
"append",
"(",
"trove_id",
")",
"classifiers",
"=",
"sorted",
"(",
"list",
"(",
"set",
"(",
"classifiers",
")",
")",
")",
"setuptools_kwargs",
"[",
"\"classifiers\"",
"]",
"=",
"classifiers",
"return",
"setuptools_kwargs"
] |
Extract the metadata from the module or dict argument.
It returns a `metadata` dictionary that provides keywords arguments
for the setuptools `setup` function.
|
[
"Extract",
"the",
"metadata",
"from",
"the",
"module",
"or",
"dict",
"argument",
"."
] |
ae16b015377250fe9df11848ea11ddaa9df54ffa
|
https://github.com/boisgera/about/blob/ae16b015377250fe9df11848ea11ddaa9df54ffa/about/__init__.py#L87-L149
|
242,597
|
donovan-duplessis/pwnurl
|
manage.py
|
profile
|
def profile(length=25):
""" Start the application under the code profiler """
from werkzeug.contrib.profiler import ProfilerMiddleware
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length])
app.run()
|
python
|
def profile(length=25):
""" Start the application under the code profiler """
from werkzeug.contrib.profiler import ProfilerMiddleware
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length])
app.run()
|
[
"def",
"profile",
"(",
"length",
"=",
"25",
")",
":",
"from",
"werkzeug",
".",
"contrib",
".",
"profiler",
"import",
"ProfilerMiddleware",
"app",
".",
"wsgi_app",
"=",
"ProfilerMiddleware",
"(",
"app",
".",
"wsgi_app",
",",
"restrictions",
"=",
"[",
"length",
"]",
")",
"app",
".",
"run",
"(",
")"
] |
Start the application under the code profiler
|
[
"Start",
"the",
"application",
"under",
"the",
"code",
"profiler"
] |
a13e27694f738228d186ea437b4d15ef5a925a87
|
https://github.com/donovan-duplessis/pwnurl/blob/a13e27694f738228d186ea437b4d15ef5a925a87/manage.py#L63-L68
|
242,598
|
donovan-duplessis/pwnurl
|
manage.py
|
_help
|
def _help():
""" Display both SQLAlchemy and Python help statements """
statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))
print statement.strip()
|
python
|
def _help():
""" Display both SQLAlchemy and Python help statements """
statement = '%s%s' % (shelp, phelp % ', '.join(cntx_.keys()))
print statement.strip()
|
[
"def",
"_help",
"(",
")",
":",
"statement",
"=",
"'%s%s'",
"%",
"(",
"shelp",
",",
"phelp",
"%",
"', '",
".",
"join",
"(",
"cntx_",
".",
"keys",
"(",
")",
")",
")",
"print",
"statement",
".",
"strip",
"(",
")"
] |
Display both SQLAlchemy and Python help statements
|
[
"Display",
"both",
"SQLAlchemy",
"and",
"Python",
"help",
"statements"
] |
a13e27694f738228d186ea437b4d15ef5a925a87
|
https://github.com/donovan-duplessis/pwnurl/blob/a13e27694f738228d186ea437b4d15ef5a925a87/manage.py#L71-L75
|
242,599
|
beylsp/unisquid
|
unisquid/liveserver.py
|
LiveServerThread.run
|
def run(self):
"""
Sets up live server, and then loops over handling http requests.
"""
try:
# Go through the list of possible ports, hoping we can find
# one that is free to use for the WSGI server.
for index, port in enumerate(self.possible_ports):
try:
self.httpd = self._create_server(port)
except socket.error as e:
if (index + 1 < len(self.possible_ports) and
e.error == errno.EADDRINUSE):
# This port is already in use, so we go on and try with
# the next one in the list.
continue
else:
# Either none of the given ports are free or the error
# is something else than "Address already in use". So
# we let that error bubble up to the main thread.
raise
else:
# A free port was found.
self.port = port
break
self.is_ready.set()
self.httpd.serve_forever()
except Exception as e:
self.error = e
self.is_ready.set()
|
python
|
def run(self):
"""
Sets up live server, and then loops over handling http requests.
"""
try:
# Go through the list of possible ports, hoping we can find
# one that is free to use for the WSGI server.
for index, port in enumerate(self.possible_ports):
try:
self.httpd = self._create_server(port)
except socket.error as e:
if (index + 1 < len(self.possible_ports) and
e.error == errno.EADDRINUSE):
# This port is already in use, so we go on and try with
# the next one in the list.
continue
else:
# Either none of the given ports are free or the error
# is something else than "Address already in use". So
# we let that error bubble up to the main thread.
raise
else:
# A free port was found.
self.port = port
break
self.is_ready.set()
self.httpd.serve_forever()
except Exception as e:
self.error = e
self.is_ready.set()
|
[
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"# Go through the list of possible ports, hoping we can find",
"# one that is free to use for the WSGI server.",
"for",
"index",
",",
"port",
"in",
"enumerate",
"(",
"self",
".",
"possible_ports",
")",
":",
"try",
":",
"self",
".",
"httpd",
"=",
"self",
".",
"_create_server",
"(",
"port",
")",
"except",
"socket",
".",
"error",
"as",
"e",
":",
"if",
"(",
"index",
"+",
"1",
"<",
"len",
"(",
"self",
".",
"possible_ports",
")",
"and",
"e",
".",
"error",
"==",
"errno",
".",
"EADDRINUSE",
")",
":",
"# This port is already in use, so we go on and try with",
"# the next one in the list.",
"continue",
"else",
":",
"# Either none of the given ports are free or the error",
"# is something else than \"Address already in use\". So",
"# we let that error bubble up to the main thread.",
"raise",
"else",
":",
"# A free port was found.",
"self",
".",
"port",
"=",
"port",
"break",
"self",
".",
"is_ready",
".",
"set",
"(",
")",
"self",
".",
"httpd",
".",
"serve_forever",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"error",
"=",
"e",
"self",
".",
"is_ready",
".",
"set",
"(",
")"
] |
Sets up live server, and then loops over handling http requests.
|
[
"Sets",
"up",
"live",
"server",
"and",
"then",
"loops",
"over",
"handling",
"http",
"requests",
"."
] |
880787a2b6c9051b7f82a7f721434819984003e2
|
https://github.com/beylsp/unisquid/blob/880787a2b6c9051b7f82a7f721434819984003e2/unisquid/liveserver.py#L29-L59
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.