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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
248,600 | Valuehorizon/valuehorizon-people | people/models.py | Person.full_name | def full_name(self):
"""
Return the title and full name
"""
return "%s %s %s %s" % (self.get_title_display(),
self.first_name,
self.other_names.replace(",", ""),
self.last_name) | python | def full_name(self):
"""
Return the title and full name
"""
return "%s %s %s %s" % (self.get_title_display(),
self.first_name,
self.other_names.replace(",", ""),
self.last_name) | [
"def",
"full_name",
"(",
"self",
")",
":",
"return",
"\"%s %s %s %s\"",
"%",
"(",
"self",
".",
"get_title_display",
"(",
")",
",",
"self",
".",
"first_name",
",",
"self",
".",
"other_names",
".",
"replace",
"(",
"\",\"",
",",
"\"\"",
")",
",",
"self",
".",
"last_name",
")"
] | Return the title and full name | [
"Return",
"the",
"title",
"and",
"full",
"name"
] | f32d9f1349c1a9384bae5ea61d10c1b1e0318401 | https://github.com/Valuehorizon/valuehorizon-people/blob/f32d9f1349c1a9384bae5ea61d10c1b1e0318401/people/models.py#L89-L96 |
248,601 | Valuehorizon/valuehorizon-people | people/models.py | Person.save | def save(self, *args, **kwargs):
"""
If date of death is specified, set is_deceased to true
"""
if self.date_of_death != None:
self.is_deceased = True
# Since we often copy and paste names from strange sources, do some basic cleanup
self.first_name = self.first_name.strip()
self.last_name = self.last_name.strip()
self.other_names = self.other_names.strip()
# Call save method
super(Person, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""
If date of death is specified, set is_deceased to true
"""
if self.date_of_death != None:
self.is_deceased = True
# Since we often copy and paste names from strange sources, do some basic cleanup
self.first_name = self.first_name.strip()
self.last_name = self.last_name.strip()
self.other_names = self.other_names.strip()
# Call save method
super(Person, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"date_of_death",
"!=",
"None",
":",
"self",
".",
"is_deceased",
"=",
"True",
"# Since we often copy and paste names from strange sources, do some basic cleanup",
"self",
".",
"first_name",
"=",
"self",
".",
"first_name",
".",
"strip",
"(",
")",
"self",
".",
"last_name",
"=",
"self",
".",
"last_name",
".",
"strip",
"(",
")",
"self",
".",
"other_names",
"=",
"self",
".",
"other_names",
".",
"strip",
"(",
")",
"# Call save method",
"super",
"(",
"Person",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | If date of death is specified, set is_deceased to true | [
"If",
"date",
"of",
"death",
"is",
"specified",
"set",
"is_deceased",
"to",
"true"
] | f32d9f1349c1a9384bae5ea61d10c1b1e0318401 | https://github.com/Valuehorizon/valuehorizon-people/blob/f32d9f1349c1a9384bae5ea61d10c1b1e0318401/people/models.py#L102-L115 |
248,602 | awacha/credolib | credolib/persistence.py | storedata | def storedata(filename=None):
"""Store the state of the current credolib workspace in a pickle file."""
if filename is None:
filename = 'credolib_state.pickle'
ns = get_ipython().user_ns
with open(filename, 'wb') as f:
d = {}
for var in ['_headers', '_loaders', '_data1d', '_data2d', '_data1dunited',
'allsamplenames', '_headers_sample', 'badfsns', '_rowavg',
'saveto_dir',
'badfsns_datcmp', 'auximages_dir', 'subtractedsamplenames', 'outputpath', 'saveto_dir_rel',
'auximages_dir_rel', 'crd_prefix']:
try:
d[var] = ns[var]
except KeyError:
warnings.warn('Skipping storage of unavailable variable "%s"' % var)
pickle.dump(d, f) | python | def storedata(filename=None):
"""Store the state of the current credolib workspace in a pickle file."""
if filename is None:
filename = 'credolib_state.pickle'
ns = get_ipython().user_ns
with open(filename, 'wb') as f:
d = {}
for var in ['_headers', '_loaders', '_data1d', '_data2d', '_data1dunited',
'allsamplenames', '_headers_sample', 'badfsns', '_rowavg',
'saveto_dir',
'badfsns_datcmp', 'auximages_dir', 'subtractedsamplenames', 'outputpath', 'saveto_dir_rel',
'auximages_dir_rel', 'crd_prefix']:
try:
d[var] = ns[var]
except KeyError:
warnings.warn('Skipping storage of unavailable variable "%s"' % var)
pickle.dump(d, f) | [
"def",
"storedata",
"(",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"'credolib_state.pickle'",
"ns",
"=",
"get_ipython",
"(",
")",
".",
"user_ns",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"d",
"=",
"{",
"}",
"for",
"var",
"in",
"[",
"'_headers'",
",",
"'_loaders'",
",",
"'_data1d'",
",",
"'_data2d'",
",",
"'_data1dunited'",
",",
"'allsamplenames'",
",",
"'_headers_sample'",
",",
"'badfsns'",
",",
"'_rowavg'",
",",
"'saveto_dir'",
",",
"'badfsns_datcmp'",
",",
"'auximages_dir'",
",",
"'subtractedsamplenames'",
",",
"'outputpath'",
",",
"'saveto_dir_rel'",
",",
"'auximages_dir_rel'",
",",
"'crd_prefix'",
"]",
":",
"try",
":",
"d",
"[",
"var",
"]",
"=",
"ns",
"[",
"var",
"]",
"except",
"KeyError",
":",
"warnings",
".",
"warn",
"(",
"'Skipping storage of unavailable variable \"%s\"'",
"%",
"var",
")",
"pickle",
".",
"dump",
"(",
"d",
",",
"f",
")"
] | Store the state of the current credolib workspace in a pickle file. | [
"Store",
"the",
"state",
"of",
"the",
"current",
"credolib",
"workspace",
"in",
"a",
"pickle",
"file",
"."
] | 11c0be3eea7257d3d6e13697d3e76ce538f2f1b2 | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/persistence.py#L8-L24 |
248,603 | awacha/credolib | credolib/persistence.py | restoredata | def restoredata(filename=None):
"""Restore the state of the credolib workspace from a pickle file."""
if filename is None:
filename = 'credolib_state.pickle'
ns = get_ipython().user_ns
with open(filename, 'rb') as f:
d = pickle.load(f)
for k in d.keys():
ns[k] = d[k] | python | def restoredata(filename=None):
"""Restore the state of the credolib workspace from a pickle file."""
if filename is None:
filename = 'credolib_state.pickle'
ns = get_ipython().user_ns
with open(filename, 'rb') as f:
d = pickle.load(f)
for k in d.keys():
ns[k] = d[k] | [
"def",
"restoredata",
"(",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"'credolib_state.pickle'",
"ns",
"=",
"get_ipython",
"(",
")",
".",
"user_ns",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"d",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"for",
"k",
"in",
"d",
".",
"keys",
"(",
")",
":",
"ns",
"[",
"k",
"]",
"=",
"d",
"[",
"k",
"]"
] | Restore the state of the credolib workspace from a pickle file. | [
"Restore",
"the",
"state",
"of",
"the",
"credolib",
"workspace",
"from",
"a",
"pickle",
"file",
"."
] | 11c0be3eea7257d3d6e13697d3e76ce538f2f1b2 | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/persistence.py#L27-L35 |
248,604 | TheOneHyer/arandomness | build/lib.linux-x86_64-3.6/arandomness/str/autocorrect.py | autocorrect | def autocorrect(query, possibilities, delta=0.75):
"""Attempts to figure out what possibility the query is
This autocorrect function is rather simple right now with plans for later
improvement. Right now, it just attempts to finish spelling a word as much
as possible, and then determines which possibility is closest to said word.
Args:
query (unicode): query to attempt to complete
possibilities (list): list of unicodes of possible answers for query
delta (float): Minimum delta similarity between query and
any given possibility for possibility to be considered.
Delta used by difflib.get_close_matches().
Returns:
unicode: best guess of correct answer
Raises:
AssertionError: raised if no matches found
Example:
.. code-block:: Python
>>> autocorrect('bowtei', ['bowtie2', 'bot'])
'bowtie2'
"""
# TODO: Make this way more robust and awesome using probability, n-grams?
possibilities = [possibility.lower() for possibility in possibilities]
# Don't waste time for exact matches
if query in possibilities:
return query
# Complete query as much as possible
options = [word for word in possibilities if word.startswith(query)]
if len(options) > 0:
possibilities = options
query = max_substring(options)
# Identify possible matches and return best match
matches = get_close_matches(query, possibilities, cutoff=delta)
# Raise error if no matches
try:
assert len(matches) > 0
except AssertionError:
raise AssertionError('No matches for "{0}" found'.format(query))
return matches[0] | python | def autocorrect(query, possibilities, delta=0.75):
"""Attempts to figure out what possibility the query is
This autocorrect function is rather simple right now with plans for later
improvement. Right now, it just attempts to finish spelling a word as much
as possible, and then determines which possibility is closest to said word.
Args:
query (unicode): query to attempt to complete
possibilities (list): list of unicodes of possible answers for query
delta (float): Minimum delta similarity between query and
any given possibility for possibility to be considered.
Delta used by difflib.get_close_matches().
Returns:
unicode: best guess of correct answer
Raises:
AssertionError: raised if no matches found
Example:
.. code-block:: Python
>>> autocorrect('bowtei', ['bowtie2', 'bot'])
'bowtie2'
"""
# TODO: Make this way more robust and awesome using probability, n-grams?
possibilities = [possibility.lower() for possibility in possibilities]
# Don't waste time for exact matches
if query in possibilities:
return query
# Complete query as much as possible
options = [word for word in possibilities if word.startswith(query)]
if len(options) > 0:
possibilities = options
query = max_substring(options)
# Identify possible matches and return best match
matches = get_close_matches(query, possibilities, cutoff=delta)
# Raise error if no matches
try:
assert len(matches) > 0
except AssertionError:
raise AssertionError('No matches for "{0}" found'.format(query))
return matches[0] | [
"def",
"autocorrect",
"(",
"query",
",",
"possibilities",
",",
"delta",
"=",
"0.75",
")",
":",
"# TODO: Make this way more robust and awesome using probability, n-grams?",
"possibilities",
"=",
"[",
"possibility",
".",
"lower",
"(",
")",
"for",
"possibility",
"in",
"possibilities",
"]",
"# Don't waste time for exact matches",
"if",
"query",
"in",
"possibilities",
":",
"return",
"query",
"# Complete query as much as possible",
"options",
"=",
"[",
"word",
"for",
"word",
"in",
"possibilities",
"if",
"word",
".",
"startswith",
"(",
"query",
")",
"]",
"if",
"len",
"(",
"options",
")",
">",
"0",
":",
"possibilities",
"=",
"options",
"query",
"=",
"max_substring",
"(",
"options",
")",
"# Identify possible matches and return best match",
"matches",
"=",
"get_close_matches",
"(",
"query",
",",
"possibilities",
",",
"cutoff",
"=",
"delta",
")",
"# Raise error if no matches",
"try",
":",
"assert",
"len",
"(",
"matches",
")",
">",
"0",
"except",
"AssertionError",
":",
"raise",
"AssertionError",
"(",
"'No matches for \"{0}\" found'",
".",
"format",
"(",
"query",
")",
")",
"return",
"matches",
"[",
"0",
"]"
] | Attempts to figure out what possibility the query is
This autocorrect function is rather simple right now with plans for later
improvement. Right now, it just attempts to finish spelling a word as much
as possible, and then determines which possibility is closest to said word.
Args:
query (unicode): query to attempt to complete
possibilities (list): list of unicodes of possible answers for query
delta (float): Minimum delta similarity between query and
any given possibility for possibility to be considered.
Delta used by difflib.get_close_matches().
Returns:
unicode: best guess of correct answer
Raises:
AssertionError: raised if no matches found
Example:
.. code-block:: Python
>>> autocorrect('bowtei', ['bowtie2', 'bot'])
'bowtie2' | [
"Attempts",
"to",
"figure",
"out",
"what",
"possibility",
"the",
"query",
"is"
] | ae9f630e9a1d67b0eb6d61644a49756de8a5268c | https://github.com/TheOneHyer/arandomness/blob/ae9f630e9a1d67b0eb6d61644a49756de8a5268c/build/lib.linux-x86_64-3.6/arandomness/str/autocorrect.py#L34-L88 |
248,605 | nir0s/serv | serv/init/base.py | Base.generate | def generate(self, overwrite):
"""Generate service files.
This exposes several comforts.
`self.files` is a list into which all generated file paths will be
appended. It is later returned by `generate` to be consumed by any
program that wants to do something with it.
`self.templates` is the directory in which all templates are
stored. New init system implementations can use this to easily
pull template files.
`self.template_prefix` is a prefix for all template files.
Since all template files should be named
`<INIT_SYS_NAME>*`, this will basically just
provide the prefix before the * for you to use.
`self.generate_into_prefix` is a prefix for the path into which
files will be generated. This is NOT the destination path for the
file when deploying the service.
`self.overwrite` automatically deals with overwriting files so that
the developer doesn't have to address this. It is provided by the API
or by the CLI and propagated.
"""
self.files = []
tmp = utils.get_tmp_dir(self.init_system, self.name)
self.templates = os.path.join(os.path.dirname(__file__), 'templates')
self.template_prefix = self.init_system
self.generate_into_prefix = os.path.join(tmp, self.name)
self.overwrite = overwrite | python | def generate(self, overwrite):
"""Generate service files.
This exposes several comforts.
`self.files` is a list into which all generated file paths will be
appended. It is later returned by `generate` to be consumed by any
program that wants to do something with it.
`self.templates` is the directory in which all templates are
stored. New init system implementations can use this to easily
pull template files.
`self.template_prefix` is a prefix for all template files.
Since all template files should be named
`<INIT_SYS_NAME>*`, this will basically just
provide the prefix before the * for you to use.
`self.generate_into_prefix` is a prefix for the path into which
files will be generated. This is NOT the destination path for the
file when deploying the service.
`self.overwrite` automatically deals with overwriting files so that
the developer doesn't have to address this. It is provided by the API
or by the CLI and propagated.
"""
self.files = []
tmp = utils.get_tmp_dir(self.init_system, self.name)
self.templates = os.path.join(os.path.dirname(__file__), 'templates')
self.template_prefix = self.init_system
self.generate_into_prefix = os.path.join(tmp, self.name)
self.overwrite = overwrite | [
"def",
"generate",
"(",
"self",
",",
"overwrite",
")",
":",
"self",
".",
"files",
"=",
"[",
"]",
"tmp",
"=",
"utils",
".",
"get_tmp_dir",
"(",
"self",
".",
"init_system",
",",
"self",
".",
"name",
")",
"self",
".",
"templates",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'templates'",
")",
"self",
".",
"template_prefix",
"=",
"self",
".",
"init_system",
"self",
".",
"generate_into_prefix",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp",
",",
"self",
".",
"name",
")",
"self",
".",
"overwrite",
"=",
"overwrite"
] | Generate service files.
This exposes several comforts.
`self.files` is a list into which all generated file paths will be
appended. It is later returned by `generate` to be consumed by any
program that wants to do something with it.
`self.templates` is the directory in which all templates are
stored. New init system implementations can use this to easily
pull template files.
`self.template_prefix` is a prefix for all template files.
Since all template files should be named
`<INIT_SYS_NAME>*`, this will basically just
provide the prefix before the * for you to use.
`self.generate_into_prefix` is a prefix for the path into which
files will be generated. This is NOT the destination path for the
file when deploying the service.
`self.overwrite` automatically deals with overwriting files so that
the developer doesn't have to address this. It is provided by the API
or by the CLI and propagated. | [
"Generate",
"service",
"files",
"."
] | 7af724ed49c0eb766c37c4b5287b043a8cf99e9c | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/base.py#L78-L109 |
248,606 | nir0s/serv | serv/init/base.py | Base.status | def status(self, **kwargs):
"""Retrieve the status of a service `name` or all services
for the current init system.
"""
self.services = dict(
init_system=self.init_system,
services=[]
) | python | def status(self, **kwargs):
"""Retrieve the status of a service `name` or all services
for the current init system.
"""
self.services = dict(
init_system=self.init_system,
services=[]
) | [
"def",
"status",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"services",
"=",
"dict",
"(",
"init_system",
"=",
"self",
".",
"init_system",
",",
"services",
"=",
"[",
"]",
")"
] | Retrieve the status of a service `name` or all services
for the current init system. | [
"Retrieve",
"the",
"status",
"of",
"a",
"service",
"name",
"or",
"all",
"services",
"for",
"the",
"current",
"init",
"system",
"."
] | 7af724ed49c0eb766c37c4b5287b043a8cf99e9c | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/base.py#L139-L146 |
248,607 | nir0s/serv | serv/init/base.py | Base.generate_file_from_template | def generate_file_from_template(self, template, destination):
"""Generate a file from a Jinja2 `template` and writes it to
`destination` using `params`.
`overwrite` allows to overwrite existing files. It is passed to
the `generate` method.
This is used by the different init implementations to generate
init scripts/configs and deploy them to the relevant directories.
Templates are looked up under init/templates/`template`.
If the `destination` directory doesn't exist, it will alert
the user and exit. We don't want to be creating any system
related directories out of the blue. The exception to the rule is
with nssm.
While it may seem a bit weird, not all relevant directories exist
out of the box. For instance, `/etc/sysconfig` doesn't necessarily
exist even if systemd is used by default.
"""
# We cast the object to a string before passing it on as py3.x
# will fail on Jinja2 if there are ints/bytes (not strings) in the
# template which will not allow `env.from_string(template)` to
# take place.
templates = str(pkgutil.get_data(__name__, os.path.join(
'templates', template)))
pretty_params = json.dumps(self.params, indent=4, sort_keys=True)
self.logger.debug(
'Rendering %s with params: %s...', template, pretty_params)
generated = jinja2.Environment().from_string(
templates).render(self.params)
self.logger.debug('Writing generated file to %s...', destination)
self._should_overwrite(destination)
with open(destination, 'w') as f:
f.write(generated)
self.files.append(destination) | python | def generate_file_from_template(self, template, destination):
"""Generate a file from a Jinja2 `template` and writes it to
`destination` using `params`.
`overwrite` allows to overwrite existing files. It is passed to
the `generate` method.
This is used by the different init implementations to generate
init scripts/configs and deploy them to the relevant directories.
Templates are looked up under init/templates/`template`.
If the `destination` directory doesn't exist, it will alert
the user and exit. We don't want to be creating any system
related directories out of the blue. The exception to the rule is
with nssm.
While it may seem a bit weird, not all relevant directories exist
out of the box. For instance, `/etc/sysconfig` doesn't necessarily
exist even if systemd is used by default.
"""
# We cast the object to a string before passing it on as py3.x
# will fail on Jinja2 if there are ints/bytes (not strings) in the
# template which will not allow `env.from_string(template)` to
# take place.
templates = str(pkgutil.get_data(__name__, os.path.join(
'templates', template)))
pretty_params = json.dumps(self.params, indent=4, sort_keys=True)
self.logger.debug(
'Rendering %s with params: %s...', template, pretty_params)
generated = jinja2.Environment().from_string(
templates).render(self.params)
self.logger.debug('Writing generated file to %s...', destination)
self._should_overwrite(destination)
with open(destination, 'w') as f:
f.write(generated)
self.files.append(destination) | [
"def",
"generate_file_from_template",
"(",
"self",
",",
"template",
",",
"destination",
")",
":",
"# We cast the object to a string before passing it on as py3.x",
"# will fail on Jinja2 if there are ints/bytes (not strings) in the",
"# template which will not allow `env.from_string(template)` to",
"# take place.",
"templates",
"=",
"str",
"(",
"pkgutil",
".",
"get_data",
"(",
"__name__",
",",
"os",
".",
"path",
".",
"join",
"(",
"'templates'",
",",
"template",
")",
")",
")",
"pretty_params",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"params",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'Rendering %s with params: %s...'",
",",
"template",
",",
"pretty_params",
")",
"generated",
"=",
"jinja2",
".",
"Environment",
"(",
")",
".",
"from_string",
"(",
"templates",
")",
".",
"render",
"(",
"self",
".",
"params",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'Writing generated file to %s...'",
",",
"destination",
")",
"self",
".",
"_should_overwrite",
"(",
"destination",
")",
"with",
"open",
"(",
"destination",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"generated",
")",
"self",
".",
"files",
".",
"append",
"(",
"destination",
")"
] | Generate a file from a Jinja2 `template` and writes it to
`destination` using `params`.
`overwrite` allows to overwrite existing files. It is passed to
the `generate` method.
This is used by the different init implementations to generate
init scripts/configs and deploy them to the relevant directories.
Templates are looked up under init/templates/`template`.
If the `destination` directory doesn't exist, it will alert
the user and exit. We don't want to be creating any system
related directories out of the blue. The exception to the rule is
with nssm.
While it may seem a bit weird, not all relevant directories exist
out of the box. For instance, `/etc/sysconfig` doesn't necessarily
exist even if systemd is used by default. | [
"Generate",
"a",
"file",
"from",
"a",
"Jinja2",
"template",
"and",
"writes",
"it",
"to",
"destination",
"using",
"params",
"."
] | 7af724ed49c0eb766c37c4b5287b043a8cf99e9c | https://github.com/nir0s/serv/blob/7af724ed49c0eb766c37c4b5287b043a8cf99e9c/serv/init/base.py#L163-L198 |
248,608 | KnowledgeLinks/rdfframework | rdfframework/rdfclass/esconversion.py | convert_value_to_es | def convert_value_to_es(value, ranges, obj, method=None):
"""
Takes an value and converts it to an elasticsearch representation
args:
value: the value to convert
ranges: the list of ranges
method: convertion method to use
'None': default -> converts the value to its json value
'missing_obj': adds attributes as if the value should have
been a rdfclass object
"""
def sub_convert(val):
"""
Returns the json value for a simple datatype or the subject uri if the
value is a rdfclass
args:
val: the value to convert
"""
if isinstance(val, BaseRdfDataType):
return val.to_json
elif isinstance(value, __MODULE__.rdfclass.RdfClassBase):
return val.subject.sparql_uri
return val
if method == "missing_obj":
rtn_obj = {
"rdf_type": [rng.sparql_uri for rng in ranges], # pylint: disable=no-member
"label": [getattr(obj, label)[0] \
for label in LABEL_FIELDS \
if hasattr(obj, label)][0]}
try:
rtn_obj['uri'] = value.sparql_uri
rtn_obj["rdfs_label"] = NSM.nouri(value.sparql_uri)
except AttributeError:
rtn_obj['uri'] = "None Specified"
rtn_obj['rdfs_label'] = sub_convert(value)
rtn_obj['value'] = rtn_obj['rdfs_label']
return rtn_obj
return sub_convert(value) | python | def convert_value_to_es(value, ranges, obj, method=None):
"""
Takes an value and converts it to an elasticsearch representation
args:
value: the value to convert
ranges: the list of ranges
method: convertion method to use
'None': default -> converts the value to its json value
'missing_obj': adds attributes as if the value should have
been a rdfclass object
"""
def sub_convert(val):
"""
Returns the json value for a simple datatype or the subject uri if the
value is a rdfclass
args:
val: the value to convert
"""
if isinstance(val, BaseRdfDataType):
return val.to_json
elif isinstance(value, __MODULE__.rdfclass.RdfClassBase):
return val.subject.sparql_uri
return val
if method == "missing_obj":
rtn_obj = {
"rdf_type": [rng.sparql_uri for rng in ranges], # pylint: disable=no-member
"label": [getattr(obj, label)[0] \
for label in LABEL_FIELDS \
if hasattr(obj, label)][0]}
try:
rtn_obj['uri'] = value.sparql_uri
rtn_obj["rdfs_label"] = NSM.nouri(value.sparql_uri)
except AttributeError:
rtn_obj['uri'] = "None Specified"
rtn_obj['rdfs_label'] = sub_convert(value)
rtn_obj['value'] = rtn_obj['rdfs_label']
return rtn_obj
return sub_convert(value) | [
"def",
"convert_value_to_es",
"(",
"value",
",",
"ranges",
",",
"obj",
",",
"method",
"=",
"None",
")",
":",
"def",
"sub_convert",
"(",
"val",
")",
":",
"\"\"\"\n Returns the json value for a simple datatype or the subject uri if the\n value is a rdfclass\n\n args:\n val: the value to convert\n \"\"\"",
"if",
"isinstance",
"(",
"val",
",",
"BaseRdfDataType",
")",
":",
"return",
"val",
".",
"to_json",
"elif",
"isinstance",
"(",
"value",
",",
"__MODULE__",
".",
"rdfclass",
".",
"RdfClassBase",
")",
":",
"return",
"val",
".",
"subject",
".",
"sparql_uri",
"return",
"val",
"if",
"method",
"==",
"\"missing_obj\"",
":",
"rtn_obj",
"=",
"{",
"\"rdf_type\"",
":",
"[",
"rng",
".",
"sparql_uri",
"for",
"rng",
"in",
"ranges",
"]",
",",
"# pylint: disable=no-member",
"\"label\"",
":",
"[",
"getattr",
"(",
"obj",
",",
"label",
")",
"[",
"0",
"]",
"for",
"label",
"in",
"LABEL_FIELDS",
"if",
"hasattr",
"(",
"obj",
",",
"label",
")",
"]",
"[",
"0",
"]",
"}",
"try",
":",
"rtn_obj",
"[",
"'uri'",
"]",
"=",
"value",
".",
"sparql_uri",
"rtn_obj",
"[",
"\"rdfs_label\"",
"]",
"=",
"NSM",
".",
"nouri",
"(",
"value",
".",
"sparql_uri",
")",
"except",
"AttributeError",
":",
"rtn_obj",
"[",
"'uri'",
"]",
"=",
"\"None Specified\"",
"rtn_obj",
"[",
"'rdfs_label'",
"]",
"=",
"sub_convert",
"(",
"value",
")",
"rtn_obj",
"[",
"'value'",
"]",
"=",
"rtn_obj",
"[",
"'rdfs_label'",
"]",
"return",
"rtn_obj",
"return",
"sub_convert",
"(",
"value",
")"
] | Takes an value and converts it to an elasticsearch representation
args:
value: the value to convert
ranges: the list of ranges
method: convertion method to use
'None': default -> converts the value to its json value
'missing_obj': adds attributes as if the value should have
been a rdfclass object | [
"Takes",
"an",
"value",
"and",
"converts",
"it",
"to",
"an",
"elasticsearch",
"representation"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/esconversion.py#L24-L65 |
248,609 | KnowledgeLinks/rdfframework | rdfframework/rdfclass/esconversion.py | get_idx_types | def get_idx_types(rng_def, ranges):
"""
Returns the elasticsearch index types for the obj
args:
rng_def: the range defintion dictionay
ranges: rdfproperty ranges
"""
idx_types = rng_def.get('kds_esIndexType', []).copy()
if not idx_types:
nested = False
for rng in ranges:
if range_is_obj(rng, __MODULE__.rdfclass):
nested = True
if nested:
idx_types.append('es_Nested')
return idx_types | python | def get_idx_types(rng_def, ranges):
"""
Returns the elasticsearch index types for the obj
args:
rng_def: the range defintion dictionay
ranges: rdfproperty ranges
"""
idx_types = rng_def.get('kds_esIndexType', []).copy()
if not idx_types:
nested = False
for rng in ranges:
if range_is_obj(rng, __MODULE__.rdfclass):
nested = True
if nested:
idx_types.append('es_Nested')
return idx_types | [
"def",
"get_idx_types",
"(",
"rng_def",
",",
"ranges",
")",
":",
"idx_types",
"=",
"rng_def",
".",
"get",
"(",
"'kds_esIndexType'",
",",
"[",
"]",
")",
".",
"copy",
"(",
")",
"if",
"not",
"idx_types",
":",
"nested",
"=",
"False",
"for",
"rng",
"in",
"ranges",
":",
"if",
"range_is_obj",
"(",
"rng",
",",
"__MODULE__",
".",
"rdfclass",
")",
":",
"nested",
"=",
"True",
"if",
"nested",
":",
"idx_types",
".",
"append",
"(",
"'es_Nested'",
")",
"return",
"idx_types"
] | Returns the elasticsearch index types for the obj
args:
rng_def: the range defintion dictionay
ranges: rdfproperty ranges | [
"Returns",
"the",
"elasticsearch",
"index",
"types",
"for",
"the",
"obj"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/esconversion.py#L67-L83 |
248,610 | KnowledgeLinks/rdfframework | rdfframework/rdfclass/esconversion.py | get_prop_range_defs | def get_prop_range_defs(class_names, def_list):
"""
Filters the range defitions based on the bound class
args:
obj: the rdffroperty instance
"""
try:
cls_options = set(class_names + ['kdr_AllClasses'])
return [rng_def for rng_def in def_list \
if not isinstance(rng_def, BlankNode) \
and cls_options.difference(\
set(rng_def.get('kds_appliesToClass', []))) < \
cls_options]
except AttributeError:
return [] | python | def get_prop_range_defs(class_names, def_list):
"""
Filters the range defitions based on the bound class
args:
obj: the rdffroperty instance
"""
try:
cls_options = set(class_names + ['kdr_AllClasses'])
return [rng_def for rng_def in def_list \
if not isinstance(rng_def, BlankNode) \
and cls_options.difference(\
set(rng_def.get('kds_appliesToClass', []))) < \
cls_options]
except AttributeError:
return [] | [
"def",
"get_prop_range_defs",
"(",
"class_names",
",",
"def_list",
")",
":",
"try",
":",
"cls_options",
"=",
"set",
"(",
"class_names",
"+",
"[",
"'kdr_AllClasses'",
"]",
")",
"return",
"[",
"rng_def",
"for",
"rng_def",
"in",
"def_list",
"if",
"not",
"isinstance",
"(",
"rng_def",
",",
"BlankNode",
")",
"and",
"cls_options",
".",
"difference",
"(",
"set",
"(",
"rng_def",
".",
"get",
"(",
"'kds_appliesToClass'",
",",
"[",
"]",
")",
")",
")",
"<",
"cls_options",
"]",
"except",
"AttributeError",
":",
"return",
"[",
"]"
] | Filters the range defitions based on the bound class
args:
obj: the rdffroperty instance | [
"Filters",
"the",
"range",
"defitions",
"based",
"on",
"the",
"bound",
"class"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/esconversion.py#L85-L101 |
248,611 | KnowledgeLinks/rdfframework | rdfframework/rdfclass/esconversion.py | range_is_obj | def range_is_obj(rng, rdfclass):
""" Test to see if range for the class should be an object
or a litteral
"""
if rng == 'rdfs_Literal':
return False
if hasattr(rdfclass, rng):
mod_class = getattr(rdfclass, rng)
for item in mod_class.cls_defs['rdf_type']:
try:
if issubclass(getattr(rdfclass, item),
rdfclass.rdfs_Literal):
return False
except AttributeError:
pass
if isinstance(mod_class, rdfclass.RdfClassMeta):
return True
return False | python | def range_is_obj(rng, rdfclass):
""" Test to see if range for the class should be an object
or a litteral
"""
if rng == 'rdfs_Literal':
return False
if hasattr(rdfclass, rng):
mod_class = getattr(rdfclass, rng)
for item in mod_class.cls_defs['rdf_type']:
try:
if issubclass(getattr(rdfclass, item),
rdfclass.rdfs_Literal):
return False
except AttributeError:
pass
if isinstance(mod_class, rdfclass.RdfClassMeta):
return True
return False | [
"def",
"range_is_obj",
"(",
"rng",
",",
"rdfclass",
")",
":",
"if",
"rng",
"==",
"'rdfs_Literal'",
":",
"return",
"False",
"if",
"hasattr",
"(",
"rdfclass",
",",
"rng",
")",
":",
"mod_class",
"=",
"getattr",
"(",
"rdfclass",
",",
"rng",
")",
"for",
"item",
"in",
"mod_class",
".",
"cls_defs",
"[",
"'rdf_type'",
"]",
":",
"try",
":",
"if",
"issubclass",
"(",
"getattr",
"(",
"rdfclass",
",",
"item",
")",
",",
"rdfclass",
".",
"rdfs_Literal",
")",
":",
"return",
"False",
"except",
"AttributeError",
":",
"pass",
"if",
"isinstance",
"(",
"mod_class",
",",
"rdfclass",
".",
"RdfClassMeta",
")",
":",
"return",
"True",
"return",
"False"
] | Test to see if range for the class should be an object
or a litteral | [
"Test",
"to",
"see",
"if",
"range",
"for",
"the",
"class",
"should",
"be",
"an",
"object",
"or",
"a",
"litteral"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/esconversion.py#L118-L135 |
248,612 | KnowledgeLinks/rdfframework | rdfframework/rdfclass/esconversion.py | get_es_value | def get_es_value(obj, def_obj):
"""
Returns the value for an object that goes into the elacticsearch 'value'
field
args:
obj: data object to update
def_obj: the class instance that has defintion values
"""
def get_dict_val(item):
"""
Returns the string representation of the dict item
"""
if isinstance(item, dict):
return str(item.get('value'))
return str(item)
value_flds = []
if def_obj.es_defs.get('kds_esValue'):
value_flds = def_obj.es_defs['kds_esValue'].copy()
else:
# pdb.set_trace()
value_flds = set(obj).difference(__ALL_IGN__)
value_flds = list(value_flds)
value_flds += __COMBINED__
try:
obj['value'] = [obj.get(label) for label in value_flds
if obj.get(label)][0]
except IndexError:
obj['value'] = ", ".join(["%s: %s" % (value.get('label'),
value.get('value'))
for prop, value in obj.items()
if isinstance(value, dict) and \
value.get('label')])
if isinstance(obj['value'], list):
obj['value'] = ", ".join([get_dict_val(item) for item in obj['value']])
else:
obj['value'] = get_dict_val(obj['value'])
if str(obj['value']).strip().endswith("/"):
obj['value'] = str(obj['value']).strip()[:-1].strip()
if not obj['value']:
obj['value'] = obj.get('uri', '')
return obj | python | def get_es_value(obj, def_obj):
"""
Returns the value for an object that goes into the elacticsearch 'value'
field
args:
obj: data object to update
def_obj: the class instance that has defintion values
"""
def get_dict_val(item):
"""
Returns the string representation of the dict item
"""
if isinstance(item, dict):
return str(item.get('value'))
return str(item)
value_flds = []
if def_obj.es_defs.get('kds_esValue'):
value_flds = def_obj.es_defs['kds_esValue'].copy()
else:
# pdb.set_trace()
value_flds = set(obj).difference(__ALL_IGN__)
value_flds = list(value_flds)
value_flds += __COMBINED__
try:
obj['value'] = [obj.get(label) for label in value_flds
if obj.get(label)][0]
except IndexError:
obj['value'] = ", ".join(["%s: %s" % (value.get('label'),
value.get('value'))
for prop, value in obj.items()
if isinstance(value, dict) and \
value.get('label')])
if isinstance(obj['value'], list):
obj['value'] = ", ".join([get_dict_val(item) for item in obj['value']])
else:
obj['value'] = get_dict_val(obj['value'])
if str(obj['value']).strip().endswith("/"):
obj['value'] = str(obj['value']).strip()[:-1].strip()
if not obj['value']:
obj['value'] = obj.get('uri', '')
return obj | [
"def",
"get_es_value",
"(",
"obj",
",",
"def_obj",
")",
":",
"def",
"get_dict_val",
"(",
"item",
")",
":",
"\"\"\"\n Returns the string representation of the dict item\n \"\"\"",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"return",
"str",
"(",
"item",
".",
"get",
"(",
"'value'",
")",
")",
"return",
"str",
"(",
"item",
")",
"value_flds",
"=",
"[",
"]",
"if",
"def_obj",
".",
"es_defs",
".",
"get",
"(",
"'kds_esValue'",
")",
":",
"value_flds",
"=",
"def_obj",
".",
"es_defs",
"[",
"'kds_esValue'",
"]",
".",
"copy",
"(",
")",
"else",
":",
"# pdb.set_trace()",
"value_flds",
"=",
"set",
"(",
"obj",
")",
".",
"difference",
"(",
"__ALL_IGN__",
")",
"value_flds",
"=",
"list",
"(",
"value_flds",
")",
"value_flds",
"+=",
"__COMBINED__",
"try",
":",
"obj",
"[",
"'value'",
"]",
"=",
"[",
"obj",
".",
"get",
"(",
"label",
")",
"for",
"label",
"in",
"value_flds",
"if",
"obj",
".",
"get",
"(",
"label",
")",
"]",
"[",
"0",
"]",
"except",
"IndexError",
":",
"obj",
"[",
"'value'",
"]",
"=",
"\", \"",
".",
"join",
"(",
"[",
"\"%s: %s\"",
"%",
"(",
"value",
".",
"get",
"(",
"'label'",
")",
",",
"value",
".",
"get",
"(",
"'value'",
")",
")",
"for",
"prop",
",",
"value",
"in",
"obj",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"value",
".",
"get",
"(",
"'label'",
")",
"]",
")",
"if",
"isinstance",
"(",
"obj",
"[",
"'value'",
"]",
",",
"list",
")",
":",
"obj",
"[",
"'value'",
"]",
"=",
"\", \"",
".",
"join",
"(",
"[",
"get_dict_val",
"(",
"item",
")",
"for",
"item",
"in",
"obj",
"[",
"'value'",
"]",
"]",
")",
"else",
":",
"obj",
"[",
"'value'",
"]",
"=",
"get_dict_val",
"(",
"obj",
"[",
"'value'",
"]",
")",
"if",
"str",
"(",
"obj",
"[",
"'value'",
"]",
")",
".",
"strip",
"(",
")",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"obj",
"[",
"'value'",
"]",
"=",
"str",
"(",
"obj",
"[",
"'value'",
"]",
")",
".",
"strip",
"(",
")",
"[",
":",
"-",
"1",
"]",
".",
"strip",
"(",
")",
"if",
"not",
"obj",
"[",
"'value'",
"]",
":",
"obj",
"[",
"'value'",
"]",
"=",
"obj",
".",
"get",
"(",
"'uri'",
",",
"''",
")",
"return",
"obj"
] | Returns the value for an object that goes into the elacticsearch 'value'
field
args:
obj: data object to update
def_obj: the class instance that has defintion values | [
"Returns",
"the",
"value",
"for",
"an",
"object",
"that",
"goes",
"into",
"the",
"elacticsearch",
"value",
"field"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/esconversion.py#L141-L184 |
248,613 | KnowledgeLinks/rdfframework | rdfframework/rdfclass/esconversion.py | get_es_label | def get_es_label(obj, def_obj):
"""
Returns object with label for an object that goes into the elacticsearch
'label' field
args:
obj: data object to update
def_obj: the class instance that has defintion values
"""
label_flds = LABEL_FIELDS
if def_obj.es_defs.get('kds_esLabel'):
label_flds = def_obj.es_defs['kds_esLabel'] + LABEL_FIELDS
try:
for label in label_flds:
if def_obj.cls_defs.get(label):
obj['label'] = def_obj.cls_defs[label][0]
break
if not obj.get('label'):
obj['label'] = def_obj.__class__.__name__.split("_")[-1]
except AttributeError:
# an attribute error is caused when the class is only
# an instance of the BaseRdfClass. We will search the rdf_type
# property and construct a label from rdf_type value
if def_obj.get('rdf_type'):
obj['label'] = def_obj['rdf_type'][-1].value[-1]
else:
obj['label'] = "no_label"
return obj | python | def get_es_label(obj, def_obj):
"""
Returns object with label for an object that goes into the elacticsearch
'label' field
args:
obj: data object to update
def_obj: the class instance that has defintion values
"""
label_flds = LABEL_FIELDS
if def_obj.es_defs.get('kds_esLabel'):
label_flds = def_obj.es_defs['kds_esLabel'] + LABEL_FIELDS
try:
for label in label_flds:
if def_obj.cls_defs.get(label):
obj['label'] = def_obj.cls_defs[label][0]
break
if not obj.get('label'):
obj['label'] = def_obj.__class__.__name__.split("_")[-1]
except AttributeError:
# an attribute error is caused when the class is only
# an instance of the BaseRdfClass. We will search the rdf_type
# property and construct a label from rdf_type value
if def_obj.get('rdf_type'):
obj['label'] = def_obj['rdf_type'][-1].value[-1]
else:
obj['label'] = "no_label"
return obj | [
"def",
"get_es_label",
"(",
"obj",
",",
"def_obj",
")",
":",
"label_flds",
"=",
"LABEL_FIELDS",
"if",
"def_obj",
".",
"es_defs",
".",
"get",
"(",
"'kds_esLabel'",
")",
":",
"label_flds",
"=",
"def_obj",
".",
"es_defs",
"[",
"'kds_esLabel'",
"]",
"+",
"LABEL_FIELDS",
"try",
":",
"for",
"label",
"in",
"label_flds",
":",
"if",
"def_obj",
".",
"cls_defs",
".",
"get",
"(",
"label",
")",
":",
"obj",
"[",
"'label'",
"]",
"=",
"def_obj",
".",
"cls_defs",
"[",
"label",
"]",
"[",
"0",
"]",
"break",
"if",
"not",
"obj",
".",
"get",
"(",
"'label'",
")",
":",
"obj",
"[",
"'label'",
"]",
"=",
"def_obj",
".",
"__class__",
".",
"__name__",
".",
"split",
"(",
"\"_\"",
")",
"[",
"-",
"1",
"]",
"except",
"AttributeError",
":",
"# an attribute error is caused when the class is only",
"# an instance of the BaseRdfClass. We will search the rdf_type",
"# property and construct a label from rdf_type value",
"if",
"def_obj",
".",
"get",
"(",
"'rdf_type'",
")",
":",
"obj",
"[",
"'label'",
"]",
"=",
"def_obj",
"[",
"'rdf_type'",
"]",
"[",
"-",
"1",
"]",
".",
"value",
"[",
"-",
"1",
"]",
"else",
":",
"obj",
"[",
"'label'",
"]",
"=",
"\"no_label\"",
"return",
"obj"
] | Returns object with label for an object that goes into the elacticsearch
'label' field
args:
obj: data object to update
def_obj: the class instance that has defintion values | [
"Returns",
"object",
"with",
"label",
"for",
"an",
"object",
"that",
"goes",
"into",
"the",
"elacticsearch",
"label",
"field"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/esconversion.py#L186-L213 |
248,614 | KnowledgeLinks/rdfframework | rdfframework/rdfclass/esconversion.py | get_es_ids | def get_es_ids(obj, def_obj):
"""
Returns the object updated with the 'id' and 'uri' fields for the
elasticsearch document
args:
obj: data object to update
def_obj: the class instance that has defintion values
"""
try:
path = ""
for base in [def_obj.__class__] + list(def_obj.__class__.__bases__):
if hasattr(base, 'es_defs') and base.es_defs:
path = "%s/%s/" % (base.es_defs['kds_esIndex'][0],
base.es_defs['kds_esDocType'][0])
continue
except KeyError:
path = ""
if def_obj.subject.type == 'uri':
obj['uri'] = def_obj.subject.clean_uri
obj['id'] = path + make_es_id(obj['uri'])
elif def_obj.subject.type == 'bnode':
obj['id'] = path + def_obj.bnode_id()
else:
obj['id'] = path + make_es_id(str(obj['value']))
return obj | python | def get_es_ids(obj, def_obj):
"""
Returns the object updated with the 'id' and 'uri' fields for the
elasticsearch document
args:
obj: data object to update
def_obj: the class instance that has defintion values
"""
try:
path = ""
for base in [def_obj.__class__] + list(def_obj.__class__.__bases__):
if hasattr(base, 'es_defs') and base.es_defs:
path = "%s/%s/" % (base.es_defs['kds_esIndex'][0],
base.es_defs['kds_esDocType'][0])
continue
except KeyError:
path = ""
if def_obj.subject.type == 'uri':
obj['uri'] = def_obj.subject.clean_uri
obj['id'] = path + make_es_id(obj['uri'])
elif def_obj.subject.type == 'bnode':
obj['id'] = path + def_obj.bnode_id()
else:
obj['id'] = path + make_es_id(str(obj['value']))
return obj | [
"def",
"get_es_ids",
"(",
"obj",
",",
"def_obj",
")",
":",
"try",
":",
"path",
"=",
"\"\"",
"for",
"base",
"in",
"[",
"def_obj",
".",
"__class__",
"]",
"+",
"list",
"(",
"def_obj",
".",
"__class__",
".",
"__bases__",
")",
":",
"if",
"hasattr",
"(",
"base",
",",
"'es_defs'",
")",
"and",
"base",
".",
"es_defs",
":",
"path",
"=",
"\"%s/%s/\"",
"%",
"(",
"base",
".",
"es_defs",
"[",
"'kds_esIndex'",
"]",
"[",
"0",
"]",
",",
"base",
".",
"es_defs",
"[",
"'kds_esDocType'",
"]",
"[",
"0",
"]",
")",
"continue",
"except",
"KeyError",
":",
"path",
"=",
"\"\"",
"if",
"def_obj",
".",
"subject",
".",
"type",
"==",
"'uri'",
":",
"obj",
"[",
"'uri'",
"]",
"=",
"def_obj",
".",
"subject",
".",
"clean_uri",
"obj",
"[",
"'id'",
"]",
"=",
"path",
"+",
"make_es_id",
"(",
"obj",
"[",
"'uri'",
"]",
")",
"elif",
"def_obj",
".",
"subject",
".",
"type",
"==",
"'bnode'",
":",
"obj",
"[",
"'id'",
"]",
"=",
"path",
"+",
"def_obj",
".",
"bnode_id",
"(",
")",
"else",
":",
"obj",
"[",
"'id'",
"]",
"=",
"path",
"+",
"make_es_id",
"(",
"str",
"(",
"obj",
"[",
"'value'",
"]",
")",
")",
"return",
"obj"
] | Returns the object updated with the 'id' and 'uri' fields for the
elasticsearch document
args:
obj: data object to update
def_obj: the class instance that has defintion values | [
"Returns",
"the",
"object",
"updated",
"with",
"the",
"id",
"and",
"uri",
"fields",
"for",
"the",
"elasticsearch",
"document"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/esconversion.py#L215-L241 |
248,615 | KnowledgeLinks/rdfframework | rdfframework/rdfclass/esconversion.py | make_es_id | def make_es_id(uri):
"""
Creates the id based off of the uri value
Args:
-----
uri: the uri to conver to an elasticsearch id
"""
try:
uri = uri.clean_uri
except AttributeError:
pass
return sha1(uri.encode()).hexdigest() | python | def make_es_id(uri):
"""
Creates the id based off of the uri value
Args:
-----
uri: the uri to conver to an elasticsearch id
"""
try:
uri = uri.clean_uri
except AttributeError:
pass
return sha1(uri.encode()).hexdigest() | [
"def",
"make_es_id",
"(",
"uri",
")",
":",
"try",
":",
"uri",
"=",
"uri",
".",
"clean_uri",
"except",
"AttributeError",
":",
"pass",
"return",
"sha1",
"(",
"uri",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")"
] | Creates the id based off of the uri value
Args:
-----
uri: the uri to conver to an elasticsearch id | [
"Creates",
"the",
"id",
"based",
"off",
"of",
"the",
"uri",
"value"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/rdfclass/esconversion.py#L243-L255 |
248,616 | tschaume/ccsgp_get_started | ccsgp_get_started/examples/gp_background.py | gp_norm | def gp_norm(infile):
"""indentify normalization region"""
inDir, outDir = getWorkDirs()
data, titles = [], []
for eidx,energy in enumerate(['19', '27', '39', '62']):
file_url = os.path.realpath(os.path.join(
inDir, 'rawdata', energy, 'pt-integrated', infile+'.dat'
))
data_import = np.loadtxt(open(file_url, 'rb'))
data_import[:,1] += eidx * 0.2
data_import[:,4] = data_import[:,3]
data_import[:,(2,3)] = 0
data.append(data_import)
titles.append(' '.join([getEnergy4Key(energy), 'GeV']))
nData = len(data)
lines = dict(
('x={}'.format(1+i*0.2), 'lc {} lt 2 lw 4'.format(default_colors[-2]))
for i in range(nData)
)
lines.update(dict(
('x={}'.format(1+i*0.2+0.02), 'lc {} lt 3 lw 4'.format(default_colors[-5]))
for i in range(nData)
))
lines.update(dict(
('x={}'.format(1+i*0.2-0.02), 'lc {} lt 3 lw 4'.format(default_colors[-5]))
for i in range(nData)
))
lines.update({'y=0.9': 'lc {} lt 1 lw 4'.format(default_colors[-2])})
charges = '++' if infile == 'rpp' else '--'
make_plot(
name = '%s/norm_range_%s' % (outDir,infile), xr = [0,2], yr = [0.9,1.7],
data = data, properties = [
'lt 1 lw 3 lc %s pt 1' % (default_colors[i]) # (i/2)%4
for i in range(nData)
], titles = titles, size = '8in,8in',
lmargin = 0.05, rmargin = 0.99, tmargin = 0.93, bmargin = 0.14,
xlabel = 'dielectron invariant mass, M_{ee} (GeV/c^{2})',
lines = lines, key = [
'maxrows 1', 'nobox', 'samplen 0.1', 'width -1', 'at graph 1,1.1'
], labels = {
'SE_{%s} / ME@_{%s}^N' % (charges, charges): (0.3, 1.3)
}, gpcalls = [
'ytics (1,"1" 1.2, "1" 1.4, "1" 1.6)', 'boxwidth 0.002',
],
) | python | def gp_norm(infile):
"""indentify normalization region"""
inDir, outDir = getWorkDirs()
data, titles = [], []
for eidx,energy in enumerate(['19', '27', '39', '62']):
file_url = os.path.realpath(os.path.join(
inDir, 'rawdata', energy, 'pt-integrated', infile+'.dat'
))
data_import = np.loadtxt(open(file_url, 'rb'))
data_import[:,1] += eidx * 0.2
data_import[:,4] = data_import[:,3]
data_import[:,(2,3)] = 0
data.append(data_import)
titles.append(' '.join([getEnergy4Key(energy), 'GeV']))
nData = len(data)
lines = dict(
('x={}'.format(1+i*0.2), 'lc {} lt 2 lw 4'.format(default_colors[-2]))
for i in range(nData)
)
lines.update(dict(
('x={}'.format(1+i*0.2+0.02), 'lc {} lt 3 lw 4'.format(default_colors[-5]))
for i in range(nData)
))
lines.update(dict(
('x={}'.format(1+i*0.2-0.02), 'lc {} lt 3 lw 4'.format(default_colors[-5]))
for i in range(nData)
))
lines.update({'y=0.9': 'lc {} lt 1 lw 4'.format(default_colors[-2])})
charges = '++' if infile == 'rpp' else '--'
make_plot(
name = '%s/norm_range_%s' % (outDir,infile), xr = [0,2], yr = [0.9,1.7],
data = data, properties = [
'lt 1 lw 3 lc %s pt 1' % (default_colors[i]) # (i/2)%4
for i in range(nData)
], titles = titles, size = '8in,8in',
lmargin = 0.05, rmargin = 0.99, tmargin = 0.93, bmargin = 0.14,
xlabel = 'dielectron invariant mass, M_{ee} (GeV/c^{2})',
lines = lines, key = [
'maxrows 1', 'nobox', 'samplen 0.1', 'width -1', 'at graph 1,1.1'
], labels = {
'SE_{%s} / ME@_{%s}^N' % (charges, charges): (0.3, 1.3)
}, gpcalls = [
'ytics (1,"1" 1.2, "1" 1.4, "1" 1.6)', 'boxwidth 0.002',
],
) | [
"def",
"gp_norm",
"(",
"infile",
")",
":",
"inDir",
",",
"outDir",
"=",
"getWorkDirs",
"(",
")",
"data",
",",
"titles",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"eidx",
",",
"energy",
"in",
"enumerate",
"(",
"[",
"'19'",
",",
"'27'",
",",
"'39'",
",",
"'62'",
"]",
")",
":",
"file_url",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"inDir",
",",
"'rawdata'",
",",
"energy",
",",
"'pt-integrated'",
",",
"infile",
"+",
"'.dat'",
")",
")",
"data_import",
"=",
"np",
".",
"loadtxt",
"(",
"open",
"(",
"file_url",
",",
"'rb'",
")",
")",
"data_import",
"[",
":",
",",
"1",
"]",
"+=",
"eidx",
"*",
"0.2",
"data_import",
"[",
":",
",",
"4",
"]",
"=",
"data_import",
"[",
":",
",",
"3",
"]",
"data_import",
"[",
":",
",",
"(",
"2",
",",
"3",
")",
"]",
"=",
"0",
"data",
".",
"append",
"(",
"data_import",
")",
"titles",
".",
"append",
"(",
"' '",
".",
"join",
"(",
"[",
"getEnergy4Key",
"(",
"energy",
")",
",",
"'GeV'",
"]",
")",
")",
"nData",
"=",
"len",
"(",
"data",
")",
"lines",
"=",
"dict",
"(",
"(",
"'x={}'",
".",
"format",
"(",
"1",
"+",
"i",
"*",
"0.2",
")",
",",
"'lc {} lt 2 lw 4'",
".",
"format",
"(",
"default_colors",
"[",
"-",
"2",
"]",
")",
")",
"for",
"i",
"in",
"range",
"(",
"nData",
")",
")",
"lines",
".",
"update",
"(",
"dict",
"(",
"(",
"'x={}'",
".",
"format",
"(",
"1",
"+",
"i",
"*",
"0.2",
"+",
"0.02",
")",
",",
"'lc {} lt 3 lw 4'",
".",
"format",
"(",
"default_colors",
"[",
"-",
"5",
"]",
")",
")",
"for",
"i",
"in",
"range",
"(",
"nData",
")",
")",
")",
"lines",
".",
"update",
"(",
"dict",
"(",
"(",
"'x={}'",
".",
"format",
"(",
"1",
"+",
"i",
"*",
"0.2",
"-",
"0.02",
")",
",",
"'lc {} lt 3 lw 4'",
".",
"format",
"(",
"default_colors",
"[",
"-",
"5",
"]",
")",
")",
"for",
"i",
"in",
"range",
"(",
"nData",
")",
")",
")",
"lines",
".",
"update",
"(",
"{",
"'y=0.9'",
":",
"'lc {} lt 1 lw 4'",
".",
"format",
"(",
"default_colors",
"[",
"-",
"2",
"]",
")",
"}",
")",
"charges",
"=",
"'++'",
"if",
"infile",
"==",
"'rpp'",
"else",
"'--'",
"make_plot",
"(",
"name",
"=",
"'%s/norm_range_%s'",
"%",
"(",
"outDir",
",",
"infile",
")",
",",
"xr",
"=",
"[",
"0",
",",
"2",
"]",
",",
"yr",
"=",
"[",
"0.9",
",",
"1.7",
"]",
",",
"data",
"=",
"data",
",",
"properties",
"=",
"[",
"'lt 1 lw 3 lc %s pt 1'",
"%",
"(",
"default_colors",
"[",
"i",
"]",
")",
"# (i/2)%4",
"for",
"i",
"in",
"range",
"(",
"nData",
")",
"]",
",",
"titles",
"=",
"titles",
",",
"size",
"=",
"'8in,8in'",
",",
"lmargin",
"=",
"0.05",
",",
"rmargin",
"=",
"0.99",
",",
"tmargin",
"=",
"0.93",
",",
"bmargin",
"=",
"0.14",
",",
"xlabel",
"=",
"'dielectron invariant mass, M_{ee} (GeV/c^{2})'",
",",
"lines",
"=",
"lines",
",",
"key",
"=",
"[",
"'maxrows 1'",
",",
"'nobox'",
",",
"'samplen 0.1'",
",",
"'width -1'",
",",
"'at graph 1,1.1'",
"]",
",",
"labels",
"=",
"{",
"'SE_{%s} / ME@_{%s}^N'",
"%",
"(",
"charges",
",",
"charges",
")",
":",
"(",
"0.3",
",",
"1.3",
")",
"}",
",",
"gpcalls",
"=",
"[",
"'ytics (1,\"1\" 1.2, \"1\" 1.4, \"1\" 1.6)'",
",",
"'boxwidth 0.002'",
",",
"]",
",",
")"
] | indentify normalization region | [
"indentify",
"normalization",
"region"
] | e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2 | https://github.com/tschaume/ccsgp_get_started/blob/e4e29844a3e6fc7574e9b4b8cd84131f28ddc3f2/ccsgp_get_started/examples/gp_background.py#L201-L245 |
248,617 | hamfist/sj | setup.py | get_version | def get_version():
"""
Get the version from the source, but without importing.
"""
with open('sj.py') as source:
for node in ast.walk(ast.parse(source.read(), 'sj.py')):
if node.__class__.__name__ == 'Assign' and \
node.targets[0].__class__.__name__ == 'Name' and \
node.targets[0].id == '__version__':
return node.value.s | python | def get_version():
"""
Get the version from the source, but without importing.
"""
with open('sj.py') as source:
for node in ast.walk(ast.parse(source.read(), 'sj.py')):
if node.__class__.__name__ == 'Assign' and \
node.targets[0].__class__.__name__ == 'Name' and \
node.targets[0].id == '__version__':
return node.value.s | [
"def",
"get_version",
"(",
")",
":",
"with",
"open",
"(",
"'sj.py'",
")",
"as",
"source",
":",
"for",
"node",
"in",
"ast",
".",
"walk",
"(",
"ast",
".",
"parse",
"(",
"source",
".",
"read",
"(",
")",
",",
"'sj.py'",
")",
")",
":",
"if",
"node",
".",
"__class__",
".",
"__name__",
"==",
"'Assign'",
"and",
"node",
".",
"targets",
"[",
"0",
"]",
".",
"__class__",
".",
"__name__",
"==",
"'Name'",
"and",
"node",
".",
"targets",
"[",
"0",
"]",
".",
"id",
"==",
"'__version__'",
":",
"return",
"node",
".",
"value",
".",
"s"
] | Get the version from the source, but without importing. | [
"Get",
"the",
"version",
"from",
"the",
"source",
"but",
"without",
"importing",
"."
] | a4c4b30285723651a1fe82c6d85b85a979d85cfc | https://github.com/hamfist/sj/blob/a4c4b30285723651a1fe82c6d85b85a979d85cfc/setup.py#L12-L21 |
248,618 | minhhoit/yacms | yacms/conf/forms.py | SettingsForm._init_field | def _init_field(self, setting, field_class, name, code=None):
"""
Initialize a field whether it is built with a custom name for a
specific translation language or not.
"""
kwargs = {
"label": setting["label"] + ":",
"required": setting["type"] in (int, float),
"initial": getattr(settings, name),
"help_text": self.format_help(setting["description"]),
}
if setting["choices"]:
field_class = forms.ChoiceField
kwargs["choices"] = setting["choices"]
field_instance = field_class(**kwargs)
code_name = ('_modeltranslation_' + code if code else '')
self.fields[name + code_name] = field_instance
css_class = field_class.__name__.lower()
field_instance.widget.attrs["class"] = css_class
if code:
field_instance.widget.attrs["class"] += " modeltranslation" | python | def _init_field(self, setting, field_class, name, code=None):
"""
Initialize a field whether it is built with a custom name for a
specific translation language or not.
"""
kwargs = {
"label": setting["label"] + ":",
"required": setting["type"] in (int, float),
"initial": getattr(settings, name),
"help_text": self.format_help(setting["description"]),
}
if setting["choices"]:
field_class = forms.ChoiceField
kwargs["choices"] = setting["choices"]
field_instance = field_class(**kwargs)
code_name = ('_modeltranslation_' + code if code else '')
self.fields[name + code_name] = field_instance
css_class = field_class.__name__.lower()
field_instance.widget.attrs["class"] = css_class
if code:
field_instance.widget.attrs["class"] += " modeltranslation" | [
"def",
"_init_field",
"(",
"self",
",",
"setting",
",",
"field_class",
",",
"name",
",",
"code",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"\"label\"",
":",
"setting",
"[",
"\"label\"",
"]",
"+",
"\":\"",
",",
"\"required\"",
":",
"setting",
"[",
"\"type\"",
"]",
"in",
"(",
"int",
",",
"float",
")",
",",
"\"initial\"",
":",
"getattr",
"(",
"settings",
",",
"name",
")",
",",
"\"help_text\"",
":",
"self",
".",
"format_help",
"(",
"setting",
"[",
"\"description\"",
"]",
")",
",",
"}",
"if",
"setting",
"[",
"\"choices\"",
"]",
":",
"field_class",
"=",
"forms",
".",
"ChoiceField",
"kwargs",
"[",
"\"choices\"",
"]",
"=",
"setting",
"[",
"\"choices\"",
"]",
"field_instance",
"=",
"field_class",
"(",
"*",
"*",
"kwargs",
")",
"code_name",
"=",
"(",
"'_modeltranslation_'",
"+",
"code",
"if",
"code",
"else",
"''",
")",
"self",
".",
"fields",
"[",
"name",
"+",
"code_name",
"]",
"=",
"field_instance",
"css_class",
"=",
"field_class",
".",
"__name__",
".",
"lower",
"(",
")",
"field_instance",
".",
"widget",
".",
"attrs",
"[",
"\"class\"",
"]",
"=",
"css_class",
"if",
"code",
":",
"field_instance",
".",
"widget",
".",
"attrs",
"[",
"\"class\"",
"]",
"+=",
"\" modeltranslation\""
] | Initialize a field whether it is built with a custom name for a
specific translation language or not. | [
"Initialize",
"a",
"field",
"whether",
"it",
"is",
"built",
"with",
"a",
"custom",
"name",
"for",
"a",
"specific",
"translation",
"language",
"or",
"not",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/conf/forms.py#L52-L72 |
248,619 | minhhoit/yacms | yacms/conf/forms.py | SettingsForm.save | def save(self):
"""
Save each of the settings to the DB.
"""
active_language = get_language()
for (name, value) in self.cleaned_data.items():
if name not in registry:
name, code = name.rsplit('_modeltranslation_', 1)
else:
code = None
setting_obj, created = Setting.objects.get_or_create(name=name)
if settings.USE_MODELTRANSLATION:
if registry[name]["translatable"]:
try:
activate(code)
except:
pass
finally:
setting_obj.value = value
activate(active_language)
else:
# Duplicate the value of the setting for every language
for code in OrderedDict(settings.LANGUAGES):
setattr(setting_obj,
build_localized_fieldname('value', code),
value)
else:
setting_obj.value = value
setting_obj.save() | python | def save(self):
"""
Save each of the settings to the DB.
"""
active_language = get_language()
for (name, value) in self.cleaned_data.items():
if name not in registry:
name, code = name.rsplit('_modeltranslation_', 1)
else:
code = None
setting_obj, created = Setting.objects.get_or_create(name=name)
if settings.USE_MODELTRANSLATION:
if registry[name]["translatable"]:
try:
activate(code)
except:
pass
finally:
setting_obj.value = value
activate(active_language)
else:
# Duplicate the value of the setting for every language
for code in OrderedDict(settings.LANGUAGES):
setattr(setting_obj,
build_localized_fieldname('value', code),
value)
else:
setting_obj.value = value
setting_obj.save() | [
"def",
"save",
"(",
"self",
")",
":",
"active_language",
"=",
"get_language",
"(",
")",
"for",
"(",
"name",
",",
"value",
")",
"in",
"self",
".",
"cleaned_data",
".",
"items",
"(",
")",
":",
"if",
"name",
"not",
"in",
"registry",
":",
"name",
",",
"code",
"=",
"name",
".",
"rsplit",
"(",
"'_modeltranslation_'",
",",
"1",
")",
"else",
":",
"code",
"=",
"None",
"setting_obj",
",",
"created",
"=",
"Setting",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"name",
")",
"if",
"settings",
".",
"USE_MODELTRANSLATION",
":",
"if",
"registry",
"[",
"name",
"]",
"[",
"\"translatable\"",
"]",
":",
"try",
":",
"activate",
"(",
"code",
")",
"except",
":",
"pass",
"finally",
":",
"setting_obj",
".",
"value",
"=",
"value",
"activate",
"(",
"active_language",
")",
"else",
":",
"# Duplicate the value of the setting for every language",
"for",
"code",
"in",
"OrderedDict",
"(",
"settings",
".",
"LANGUAGES",
")",
":",
"setattr",
"(",
"setting_obj",
",",
"build_localized_fieldname",
"(",
"'value'",
",",
"code",
")",
",",
"value",
")",
"else",
":",
"setting_obj",
".",
"value",
"=",
"value",
"setting_obj",
".",
"save",
"(",
")"
] | Save each of the settings to the DB. | [
"Save",
"each",
"of",
"the",
"settings",
"to",
"the",
"DB",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/conf/forms.py#L91-L119 |
248,620 | minhhoit/yacms | yacms/conf/forms.py | SettingsForm.format_help | def format_help(self, description):
"""
Format the setting's description into HTML.
"""
for bold in ("``", "*"):
parts = []
if description is None:
description = ""
for i, s in enumerate(description.split(bold)):
parts.append(s if i % 2 == 0 else "<b>%s</b>" % s)
description = "".join(parts)
description = urlize(description, autoescape=False)
return mark_safe(description.replace("\n", "<br>")) | python | def format_help(self, description):
"""
Format the setting's description into HTML.
"""
for bold in ("``", "*"):
parts = []
if description is None:
description = ""
for i, s in enumerate(description.split(bold)):
parts.append(s if i % 2 == 0 else "<b>%s</b>" % s)
description = "".join(parts)
description = urlize(description, autoescape=False)
return mark_safe(description.replace("\n", "<br>")) | [
"def",
"format_help",
"(",
"self",
",",
"description",
")",
":",
"for",
"bold",
"in",
"(",
"\"``\"",
",",
"\"*\"",
")",
":",
"parts",
"=",
"[",
"]",
"if",
"description",
"is",
"None",
":",
"description",
"=",
"\"\"",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"description",
".",
"split",
"(",
"bold",
")",
")",
":",
"parts",
".",
"append",
"(",
"s",
"if",
"i",
"%",
"2",
"==",
"0",
"else",
"\"<b>%s</b>\"",
"%",
"s",
")",
"description",
"=",
"\"\"",
".",
"join",
"(",
"parts",
")",
"description",
"=",
"urlize",
"(",
"description",
",",
"autoescape",
"=",
"False",
")",
"return",
"mark_safe",
"(",
"description",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"<br>\"",
")",
")"
] | Format the setting's description into HTML. | [
"Format",
"the",
"setting",
"s",
"description",
"into",
"HTML",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/conf/forms.py#L121-L133 |
248,621 | calvinku96/labreporthelper | labreporthelper/bestfit/polyfit.py | PolyFit.bestfit_func | def bestfit_func(self, bestfit_x):
"""
Returns bestfit_y value
args:
bestfit_x: scalar, array_like
x value
return: scalar, array_like
bestfit y value
"""
bestfit_x = np.array(bestfit_x)
if not self.done_bestfit:
raise KeyError("Do do_bestfit first")
bestfit_y = 0
for idx, val in enumerate(self.fit_args):
bestfit_y += val * (bestfit_x **
(self.args.get("degree", 1) - idx))
return bestfit_y | python | def bestfit_func(self, bestfit_x):
"""
Returns bestfit_y value
args:
bestfit_x: scalar, array_like
x value
return: scalar, array_like
bestfit y value
"""
bestfit_x = np.array(bestfit_x)
if not self.done_bestfit:
raise KeyError("Do do_bestfit first")
bestfit_y = 0
for idx, val in enumerate(self.fit_args):
bestfit_y += val * (bestfit_x **
(self.args.get("degree", 1) - idx))
return bestfit_y | [
"def",
"bestfit_func",
"(",
"self",
",",
"bestfit_x",
")",
":",
"bestfit_x",
"=",
"np",
".",
"array",
"(",
"bestfit_x",
")",
"if",
"not",
"self",
".",
"done_bestfit",
":",
"raise",
"KeyError",
"(",
"\"Do do_bestfit first\"",
")",
"bestfit_y",
"=",
"0",
"for",
"idx",
",",
"val",
"in",
"enumerate",
"(",
"self",
".",
"fit_args",
")",
":",
"bestfit_y",
"+=",
"val",
"*",
"(",
"bestfit_x",
"**",
"(",
"self",
".",
"args",
".",
"get",
"(",
"\"degree\"",
",",
"1",
")",
"-",
"idx",
")",
")",
"return",
"bestfit_y"
] | Returns bestfit_y value
args:
bestfit_x: scalar, array_like
x value
return: scalar, array_like
bestfit y value | [
"Returns",
"bestfit_y",
"value"
] | 4d436241f389c02eb188c313190df62ab28c3763 | https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/bestfit/polyfit.py#L36-L53 |
248,622 | minhhoit/yacms | yacms/accounts/views.py | login | def login(request, template="accounts/account_login.html",
form_class=LoginForm, extra_context=None):
"""
Login form.
"""
form = form_class(request.POST or None)
if request.method == "POST" and form.is_valid():
authenticated_user = form.save()
info(request, _("Successfully logged in"))
auth_login(request, authenticated_user)
return login_redirect(request)
context = {"form": form, "title": _("Log in")}
context.update(extra_context or {})
return TemplateResponse(request, template, context) | python | def login(request, template="accounts/account_login.html",
form_class=LoginForm, extra_context=None):
"""
Login form.
"""
form = form_class(request.POST or None)
if request.method == "POST" and form.is_valid():
authenticated_user = form.save()
info(request, _("Successfully logged in"))
auth_login(request, authenticated_user)
return login_redirect(request)
context = {"form": form, "title": _("Log in")}
context.update(extra_context or {})
return TemplateResponse(request, template, context) | [
"def",
"login",
"(",
"request",
",",
"template",
"=",
"\"accounts/account_login.html\"",
",",
"form_class",
"=",
"LoginForm",
",",
"extra_context",
"=",
"None",
")",
":",
"form",
"=",
"form_class",
"(",
"request",
".",
"POST",
"or",
"None",
")",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
"and",
"form",
".",
"is_valid",
"(",
")",
":",
"authenticated_user",
"=",
"form",
".",
"save",
"(",
")",
"info",
"(",
"request",
",",
"_",
"(",
"\"Successfully logged in\"",
")",
")",
"auth_login",
"(",
"request",
",",
"authenticated_user",
")",
"return",
"login_redirect",
"(",
"request",
")",
"context",
"=",
"{",
"\"form\"",
":",
"form",
",",
"\"title\"",
":",
"_",
"(",
"\"Log in\"",
")",
"}",
"context",
".",
"update",
"(",
"extra_context",
"or",
"{",
"}",
")",
"return",
"TemplateResponse",
"(",
"request",
",",
"template",
",",
"context",
")"
] | Login form. | [
"Login",
"form",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/views.py#L22-L35 |
248,623 | minhhoit/yacms | yacms/accounts/views.py | signup | def signup(request, template="accounts/account_signup.html",
extra_context=None):
"""
Signup form.
"""
profile_form = get_profile_form()
form = profile_form(request.POST or None, request.FILES or None)
if request.method == "POST" and form.is_valid():
new_user = form.save()
if not new_user.is_active:
if settings.ACCOUNTS_APPROVAL_REQUIRED:
send_approve_mail(request, new_user)
info(request, _("Thanks for signing up! You'll receive "
"an email when your account is activated."))
else:
send_verification_mail(request, new_user, "signup_verify")
info(request, _("A verification email has been sent with "
"a link for activating your account."))
return redirect(next_url(request) or "/")
else:
info(request, _("Successfully signed up"))
auth_login(request, new_user)
return login_redirect(request)
context = {"form": form, "title": _("Sign up")}
context.update(extra_context or {})
return TemplateResponse(request, template, context) | python | def signup(request, template="accounts/account_signup.html",
extra_context=None):
"""
Signup form.
"""
profile_form = get_profile_form()
form = profile_form(request.POST or None, request.FILES or None)
if request.method == "POST" and form.is_valid():
new_user = form.save()
if not new_user.is_active:
if settings.ACCOUNTS_APPROVAL_REQUIRED:
send_approve_mail(request, new_user)
info(request, _("Thanks for signing up! You'll receive "
"an email when your account is activated."))
else:
send_verification_mail(request, new_user, "signup_verify")
info(request, _("A verification email has been sent with "
"a link for activating your account."))
return redirect(next_url(request) or "/")
else:
info(request, _("Successfully signed up"))
auth_login(request, new_user)
return login_redirect(request)
context = {"form": form, "title": _("Sign up")}
context.update(extra_context or {})
return TemplateResponse(request, template, context) | [
"def",
"signup",
"(",
"request",
",",
"template",
"=",
"\"accounts/account_signup.html\"",
",",
"extra_context",
"=",
"None",
")",
":",
"profile_form",
"=",
"get_profile_form",
"(",
")",
"form",
"=",
"profile_form",
"(",
"request",
".",
"POST",
"or",
"None",
",",
"request",
".",
"FILES",
"or",
"None",
")",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
"and",
"form",
".",
"is_valid",
"(",
")",
":",
"new_user",
"=",
"form",
".",
"save",
"(",
")",
"if",
"not",
"new_user",
".",
"is_active",
":",
"if",
"settings",
".",
"ACCOUNTS_APPROVAL_REQUIRED",
":",
"send_approve_mail",
"(",
"request",
",",
"new_user",
")",
"info",
"(",
"request",
",",
"_",
"(",
"\"Thanks for signing up! You'll receive \"",
"\"an email when your account is activated.\"",
")",
")",
"else",
":",
"send_verification_mail",
"(",
"request",
",",
"new_user",
",",
"\"signup_verify\"",
")",
"info",
"(",
"request",
",",
"_",
"(",
"\"A verification email has been sent with \"",
"\"a link for activating your account.\"",
")",
")",
"return",
"redirect",
"(",
"next_url",
"(",
"request",
")",
"or",
"\"/\"",
")",
"else",
":",
"info",
"(",
"request",
",",
"_",
"(",
"\"Successfully signed up\"",
")",
")",
"auth_login",
"(",
"request",
",",
"new_user",
")",
"return",
"login_redirect",
"(",
"request",
")",
"context",
"=",
"{",
"\"form\"",
":",
"form",
",",
"\"title\"",
":",
"_",
"(",
"\"Sign up\"",
")",
"}",
"context",
".",
"update",
"(",
"extra_context",
"or",
"{",
"}",
")",
"return",
"TemplateResponse",
"(",
"request",
",",
"template",
",",
"context",
")"
] | Signup form. | [
"Signup",
"form",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/views.py#L47-L72 |
248,624 | minhhoit/yacms | yacms/accounts/views.py | signup_verify | def signup_verify(request, uidb36=None, token=None):
"""
View for the link in the verification email sent to a new user
when they create an account and ``ACCOUNTS_VERIFICATION_REQUIRED``
is set to ``True``. Activates the user and logs them in,
redirecting to the URL they tried to access when signing up.
"""
user = authenticate(uidb36=uidb36, token=token, is_active=False)
if user is not None:
user.is_active = True
user.save()
auth_login(request, user)
info(request, _("Successfully signed up"))
return login_redirect(request)
else:
error(request, _("The link you clicked is no longer valid."))
return redirect("/") | python | def signup_verify(request, uidb36=None, token=None):
"""
View for the link in the verification email sent to a new user
when they create an account and ``ACCOUNTS_VERIFICATION_REQUIRED``
is set to ``True``. Activates the user and logs them in,
redirecting to the URL they tried to access when signing up.
"""
user = authenticate(uidb36=uidb36, token=token, is_active=False)
if user is not None:
user.is_active = True
user.save()
auth_login(request, user)
info(request, _("Successfully signed up"))
return login_redirect(request)
else:
error(request, _("The link you clicked is no longer valid."))
return redirect("/") | [
"def",
"signup_verify",
"(",
"request",
",",
"uidb36",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"user",
"=",
"authenticate",
"(",
"uidb36",
"=",
"uidb36",
",",
"token",
"=",
"token",
",",
"is_active",
"=",
"False",
")",
"if",
"user",
"is",
"not",
"None",
":",
"user",
".",
"is_active",
"=",
"True",
"user",
".",
"save",
"(",
")",
"auth_login",
"(",
"request",
",",
"user",
")",
"info",
"(",
"request",
",",
"_",
"(",
"\"Successfully signed up\"",
")",
")",
"return",
"login_redirect",
"(",
"request",
")",
"else",
":",
"error",
"(",
"request",
",",
"_",
"(",
"\"The link you clicked is no longer valid.\"",
")",
")",
"return",
"redirect",
"(",
"\"/\"",
")"
] | View for the link in the verification email sent to a new user
when they create an account and ``ACCOUNTS_VERIFICATION_REQUIRED``
is set to ``True``. Activates the user and logs them in,
redirecting to the URL they tried to access when signing up. | [
"View",
"for",
"the",
"link",
"in",
"the",
"verification",
"email",
"sent",
"to",
"a",
"new",
"user",
"when",
"they",
"create",
"an",
"account",
"and",
"ACCOUNTS_VERIFICATION_REQUIRED",
"is",
"set",
"to",
"True",
".",
"Activates",
"the",
"user",
"and",
"logs",
"them",
"in",
"redirecting",
"to",
"the",
"URL",
"they",
"tried",
"to",
"access",
"when",
"signing",
"up",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/views.py#L75-L91 |
248,625 | minhhoit/yacms | yacms/accounts/views.py | profile | def profile(request, username, template="accounts/account_profile.html",
extra_context=None):
"""
Display a profile.
"""
lookup = {"username__iexact": username, "is_active": True}
context = {"profile_user": get_object_or_404(User, **lookup)}
context.update(extra_context or {})
return TemplateResponse(request, template, context) | python | def profile(request, username, template="accounts/account_profile.html",
extra_context=None):
"""
Display a profile.
"""
lookup = {"username__iexact": username, "is_active": True}
context = {"profile_user": get_object_or_404(User, **lookup)}
context.update(extra_context or {})
return TemplateResponse(request, template, context) | [
"def",
"profile",
"(",
"request",
",",
"username",
",",
"template",
"=",
"\"accounts/account_profile.html\"",
",",
"extra_context",
"=",
"None",
")",
":",
"lookup",
"=",
"{",
"\"username__iexact\"",
":",
"username",
",",
"\"is_active\"",
":",
"True",
"}",
"context",
"=",
"{",
"\"profile_user\"",
":",
"get_object_or_404",
"(",
"User",
",",
"*",
"*",
"lookup",
")",
"}",
"context",
".",
"update",
"(",
"extra_context",
"or",
"{",
"}",
")",
"return",
"TemplateResponse",
"(",
"request",
",",
"template",
",",
"context",
")"
] | Display a profile. | [
"Display",
"a",
"profile",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/views.py#L103-L111 |
248,626 | minhhoit/yacms | yacms/accounts/views.py | profile_update | def profile_update(request, template="accounts/account_profile_update.html",
extra_context=None):
"""
Profile update form.
"""
profile_form = get_profile_form()
form = profile_form(request.POST or None, request.FILES or None,
instance=request.user)
if request.method == "POST" and form.is_valid():
user = form.save()
info(request, _("Profile updated"))
try:
return redirect("profile", username=user.username)
except NoReverseMatch:
return redirect("profile_update")
context = {"form": form, "title": _("Update Profile")}
context.update(extra_context or {})
return TemplateResponse(request, template, context) | python | def profile_update(request, template="accounts/account_profile_update.html",
extra_context=None):
"""
Profile update form.
"""
profile_form = get_profile_form()
form = profile_form(request.POST or None, request.FILES or None,
instance=request.user)
if request.method == "POST" and form.is_valid():
user = form.save()
info(request, _("Profile updated"))
try:
return redirect("profile", username=user.username)
except NoReverseMatch:
return redirect("profile_update")
context = {"form": form, "title": _("Update Profile")}
context.update(extra_context or {})
return TemplateResponse(request, template, context) | [
"def",
"profile_update",
"(",
"request",
",",
"template",
"=",
"\"accounts/account_profile_update.html\"",
",",
"extra_context",
"=",
"None",
")",
":",
"profile_form",
"=",
"get_profile_form",
"(",
")",
"form",
"=",
"profile_form",
"(",
"request",
".",
"POST",
"or",
"None",
",",
"request",
".",
"FILES",
"or",
"None",
",",
"instance",
"=",
"request",
".",
"user",
")",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
"and",
"form",
".",
"is_valid",
"(",
")",
":",
"user",
"=",
"form",
".",
"save",
"(",
")",
"info",
"(",
"request",
",",
"_",
"(",
"\"Profile updated\"",
")",
")",
"try",
":",
"return",
"redirect",
"(",
"\"profile\"",
",",
"username",
"=",
"user",
".",
"username",
")",
"except",
"NoReverseMatch",
":",
"return",
"redirect",
"(",
"\"profile_update\"",
")",
"context",
"=",
"{",
"\"form\"",
":",
"form",
",",
"\"title\"",
":",
"_",
"(",
"\"Update Profile\"",
")",
"}",
"context",
".",
"update",
"(",
"extra_context",
"or",
"{",
"}",
")",
"return",
"TemplateResponse",
"(",
"request",
",",
"template",
",",
"context",
")"
] | Profile update form. | [
"Profile",
"update",
"form",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/accounts/views.py#L124-L141 |
248,627 | jtpaasch/simplygithub | simplygithub/branches.py | get_branch_sha | def get_branch_sha(profile, name):
"""Get the SHA a branch's HEAD points to.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch.
Returns:
The requested SHA.
"""
ref = "heads/" + name
data = refs.get_ref(profile, ref)
head = data.get("head")
sha = head.get("sha")
return sha | python | def get_branch_sha(profile, name):
"""Get the SHA a branch's HEAD points to.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch.
Returns:
The requested SHA.
"""
ref = "heads/" + name
data = refs.get_ref(profile, ref)
head = data.get("head")
sha = head.get("sha")
return sha | [
"def",
"get_branch_sha",
"(",
"profile",
",",
"name",
")",
":",
"ref",
"=",
"\"heads/\"",
"+",
"name",
"data",
"=",
"refs",
".",
"get_ref",
"(",
"profile",
",",
"ref",
")",
"head",
"=",
"data",
".",
"get",
"(",
"\"head\"",
")",
"sha",
"=",
"head",
".",
"get",
"(",
"\"sha\"",
")",
"return",
"sha"
] | Get the SHA a branch's HEAD points to.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch.
Returns:
The requested SHA. | [
"Get",
"the",
"SHA",
"a",
"branch",
"s",
"HEAD",
"points",
"to",
"."
] | b77506275ec276ce90879bf1ea9299a79448b903 | https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/branches.py#L8-L29 |
248,628 | jtpaasch/simplygithub | simplygithub/branches.py | get_branch | def get_branch(profile, name):
"""Fetch a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch to fetch.
Returns:
A dict with data baout the branch.
"""
ref = "heads/" + name
data = refs.get_ref(profile, ref)
return data | python | def get_branch(profile, name):
"""Fetch a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch to fetch.
Returns:
A dict with data baout the branch.
"""
ref = "heads/" + name
data = refs.get_ref(profile, ref)
return data | [
"def",
"get_branch",
"(",
"profile",
",",
"name",
")",
":",
"ref",
"=",
"\"heads/\"",
"+",
"name",
"data",
"=",
"refs",
".",
"get_ref",
"(",
"profile",
",",
"ref",
")",
"return",
"data"
] | Fetch a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch to fetch.
Returns:
A dict with data baout the branch. | [
"Fetch",
"a",
"branch",
"."
] | b77506275ec276ce90879bf1ea9299a79448b903 | https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/branches.py#L50-L69 |
248,629 | jtpaasch/simplygithub | simplygithub/branches.py | create_branch | def create_branch(profile, name, branch_off):
"""Create a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the new branch.
branch_off
The name of a branch to create the new branch off of.
Returns:
A dict with data about the new branch.
"""
branch_off_sha = get_branch_sha(profile, branch_off)
ref = "heads/" + name
data = refs.create_ref(profile, ref, branch_off_sha)
return data | python | def create_branch(profile, name, branch_off):
"""Create a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the new branch.
branch_off
The name of a branch to create the new branch off of.
Returns:
A dict with data about the new branch.
"""
branch_off_sha = get_branch_sha(profile, branch_off)
ref = "heads/" + name
data = refs.create_ref(profile, ref, branch_off_sha)
return data | [
"def",
"create_branch",
"(",
"profile",
",",
"name",
",",
"branch_off",
")",
":",
"branch_off_sha",
"=",
"get_branch_sha",
"(",
"profile",
",",
"branch_off",
")",
"ref",
"=",
"\"heads/\"",
"+",
"name",
"data",
"=",
"refs",
".",
"create_ref",
"(",
"profile",
",",
"ref",
",",
"branch_off_sha",
")",
"return",
"data"
] | Create a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the new branch.
branch_off
The name of a branch to create the new branch off of.
Returns:
A dict with data about the new branch. | [
"Create",
"a",
"branch",
"."
] | b77506275ec276ce90879bf1ea9299a79448b903 | https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/branches.py#L72-L95 |
248,630 | jtpaasch/simplygithub | simplygithub/branches.py | update_branch | def update_branch(profile, name, sha):
"""Move a branch's HEAD to a new SHA.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch to update.
sha
The commit SHA to point the branch's HEAD to.
Returns:
A dict with data about the branch.
"""
ref = "heads/" + name
data = refs.update_ref(profile, ref, sha)
return data | python | def update_branch(profile, name, sha):
"""Move a branch's HEAD to a new SHA.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch to update.
sha
The commit SHA to point the branch's HEAD to.
Returns:
A dict with data about the branch.
"""
ref = "heads/" + name
data = refs.update_ref(profile, ref, sha)
return data | [
"def",
"update_branch",
"(",
"profile",
",",
"name",
",",
"sha",
")",
":",
"ref",
"=",
"\"heads/\"",
"+",
"name",
"data",
"=",
"refs",
".",
"update_ref",
"(",
"profile",
",",
"ref",
",",
"sha",
")",
"return",
"data"
] | Move a branch's HEAD to a new SHA.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch to update.
sha
The commit SHA to point the branch's HEAD to.
Returns:
A dict with data about the branch. | [
"Move",
"a",
"branch",
"s",
"HEAD",
"to",
"a",
"new",
"SHA",
"."
] | b77506275ec276ce90879bf1ea9299a79448b903 | https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/branches.py#L98-L120 |
248,631 | jtpaasch/simplygithub | simplygithub/branches.py | delete_branch | def delete_branch(profile, name):
"""Delete a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch to delete.
Returns:
The response of the DELETE request.
"""
ref = "heads/" + name
data = refs.delete_ref(profile, ref)
return data | python | def delete_branch(profile, name):
"""Delete a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch to delete.
Returns:
The response of the DELETE request.
"""
ref = "heads/" + name
data = refs.delete_ref(profile, ref)
return data | [
"def",
"delete_branch",
"(",
"profile",
",",
"name",
")",
":",
"ref",
"=",
"\"heads/\"",
"+",
"name",
"data",
"=",
"refs",
".",
"delete_ref",
"(",
"profile",
",",
"ref",
")",
"return",
"data"
] | Delete a branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch to delete.
Returns:
The response of the DELETE request. | [
"Delete",
"a",
"branch",
"."
] | b77506275ec276ce90879bf1ea9299a79448b903 | https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/branches.py#L123-L142 |
248,632 | jtpaasch/simplygithub | simplygithub/branches.py | merge | def merge(profile, branch, merge_into):
"""Merge a branch into another branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
branch
The name of the branch to merge.
merge_into
The name of the branch you want to merge into.
Returns:
A dict wtih data about the merge.
"""
data = merges.merge(profile, branch, merge_into)
return data | python | def merge(profile, branch, merge_into):
"""Merge a branch into another branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
branch
The name of the branch to merge.
merge_into
The name of the branch you want to merge into.
Returns:
A dict wtih data about the merge.
"""
data = merges.merge(profile, branch, merge_into)
return data | [
"def",
"merge",
"(",
"profile",
",",
"branch",
",",
"merge_into",
")",
":",
"data",
"=",
"merges",
".",
"merge",
"(",
"profile",
",",
"branch",
",",
"merge_into",
")",
"return",
"data"
] | Merge a branch into another branch.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
branch
The name of the branch to merge.
merge_into
The name of the branch you want to merge into.
Returns:
A dict wtih data about the merge. | [
"Merge",
"a",
"branch",
"into",
"another",
"branch",
"."
] | b77506275ec276ce90879bf1ea9299a79448b903 | https://github.com/jtpaasch/simplygithub/blob/b77506275ec276ce90879bf1ea9299a79448b903/simplygithub/branches.py#L145-L166 |
248,633 | 20c/xbahn | xbahn/mixins.py | EventMixin.has_callbacks | def has_callbacks(self, name):
"""
Returns True if there are callbacks attached to the specified
event name.
Returns False if not
"""
r = self.event_listeners.get(name)
if not r:
return False
return len(r) > 0 | python | def has_callbacks(self, name):
"""
Returns True if there are callbacks attached to the specified
event name.
Returns False if not
"""
r = self.event_listeners.get(name)
if not r:
return False
return len(r) > 0 | [
"def",
"has_callbacks",
"(",
"self",
",",
"name",
")",
":",
"r",
"=",
"self",
".",
"event_listeners",
".",
"get",
"(",
"name",
")",
"if",
"not",
"r",
":",
"return",
"False",
"return",
"len",
"(",
"r",
")",
">",
"0"
] | Returns True if there are callbacks attached to the specified
event name.
Returns False if not | [
"Returns",
"True",
"if",
"there",
"are",
"callbacks",
"attached",
"to",
"the",
"specified",
"event",
"name",
"."
] | afb27b0576841338a366d7cac0200a782bd84be6 | https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/mixins.py#L35-L45 |
248,634 | 20c/xbahn | xbahn/mixins.py | EventMixin.on | def on(self, name, callback, once=False):
"""
Adds a callback to the event specified by name
once <bool> if True the callback will be removed once it's been
triggered
"""
if name not in self.event_listeners:
self.event_listeners[name] = []
self.event_listeners[name].append((callback, once)) | python | def on(self, name, callback, once=False):
"""
Adds a callback to the event specified by name
once <bool> if True the callback will be removed once it's been
triggered
"""
if name not in self.event_listeners:
self.event_listeners[name] = []
self.event_listeners[name].append((callback, once)) | [
"def",
"on",
"(",
"self",
",",
"name",
",",
"callback",
",",
"once",
"=",
"False",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"event_listeners",
":",
"self",
".",
"event_listeners",
"[",
"name",
"]",
"=",
"[",
"]",
"self",
".",
"event_listeners",
"[",
"name",
"]",
".",
"append",
"(",
"(",
"callback",
",",
"once",
")",
")"
] | Adds a callback to the event specified by name
once <bool> if True the callback will be removed once it's been
triggered | [
"Adds",
"a",
"callback",
"to",
"the",
"event",
"specified",
"by",
"name"
] | afb27b0576841338a366d7cac0200a782bd84be6 | https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/mixins.py#L47-L57 |
248,635 | 20c/xbahn | xbahn/mixins.py | EventMixin.off | def off(self, name, callback, once=False):
"""
Removes callback to the event specified by name
"""
if name not in self.event_listeners:
return
self.event_listeners[name].remove((callback, once)) | python | def off(self, name, callback, once=False):
"""
Removes callback to the event specified by name
"""
if name not in self.event_listeners:
return
self.event_listeners[name].remove((callback, once)) | [
"def",
"off",
"(",
"self",
",",
"name",
",",
"callback",
",",
"once",
"=",
"False",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"event_listeners",
":",
"return",
"self",
".",
"event_listeners",
"[",
"name",
"]",
".",
"remove",
"(",
"(",
"callback",
",",
"once",
")",
")"
] | Removes callback to the event specified by name | [
"Removes",
"callback",
"to",
"the",
"event",
"specified",
"by",
"name"
] | afb27b0576841338a366d7cac0200a782bd84be6 | https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/mixins.py#L59-L67 |
248,636 | 20c/xbahn | xbahn/mixins.py | EventMixin.trigger | def trigger(self, name, *args, **kwargs):
"""
Triggers the event specified by name and passes
self in keyword argument "event_origin"
All additional arguments and keyword arguments are passed
through as well
"""
mark_remove = []
for callback, once in self.event_listeners.get(name, []):
callback(event_origin=self, *args, **kwargs)
if once:
mark_remove.append( (callback, once) )
for callback, once in mark_remove:
self.off(name, callback, once=once) | python | def trigger(self, name, *args, **kwargs):
"""
Triggers the event specified by name and passes
self in keyword argument "event_origin"
All additional arguments and keyword arguments are passed
through as well
"""
mark_remove = []
for callback, once in self.event_listeners.get(name, []):
callback(event_origin=self, *args, **kwargs)
if once:
mark_remove.append( (callback, once) )
for callback, once in mark_remove:
self.off(name, callback, once=once) | [
"def",
"trigger",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"mark_remove",
"=",
"[",
"]",
"for",
"callback",
",",
"once",
"in",
"self",
".",
"event_listeners",
".",
"get",
"(",
"name",
",",
"[",
"]",
")",
":",
"callback",
"(",
"event_origin",
"=",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"once",
":",
"mark_remove",
".",
"append",
"(",
"(",
"callback",
",",
"once",
")",
")",
"for",
"callback",
",",
"once",
"in",
"mark_remove",
":",
"self",
".",
"off",
"(",
"name",
",",
"callback",
",",
"once",
"=",
"once",
")"
] | Triggers the event specified by name and passes
self in keyword argument "event_origin"
All additional arguments and keyword arguments are passed
through as well | [
"Triggers",
"the",
"event",
"specified",
"by",
"name",
"and",
"passes",
"self",
"in",
"keyword",
"argument",
"event_origin"
] | afb27b0576841338a366d7cac0200a782bd84be6 | https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/mixins.py#L69-L85 |
248,637 | ludeeus/pyruter | pyruter/api.py | Departures.get_final_destination | async def get_final_destination(self):
"""Get a list of final destinations for a stop."""
dest = []
await self.get_departures()
for departure in self._departures:
dep = {}
dep['line'] = departure.get('line')
dep['destination'] = departure.get('destination')
dest.append(dep)
return [dict(t) for t in {tuple(d.items()) for d in dest}] | python | async def get_final_destination(self):
"""Get a list of final destinations for a stop."""
dest = []
await self.get_departures()
for departure in self._departures:
dep = {}
dep['line'] = departure.get('line')
dep['destination'] = departure.get('destination')
dest.append(dep)
return [dict(t) for t in {tuple(d.items()) for d in dest}] | [
"async",
"def",
"get_final_destination",
"(",
"self",
")",
":",
"dest",
"=",
"[",
"]",
"await",
"self",
".",
"get_departures",
"(",
")",
"for",
"departure",
"in",
"self",
".",
"_departures",
":",
"dep",
"=",
"{",
"}",
"dep",
"[",
"'line'",
"]",
"=",
"departure",
".",
"get",
"(",
"'line'",
")",
"dep",
"[",
"'destination'",
"]",
"=",
"departure",
".",
"get",
"(",
"'destination'",
")",
"dest",
".",
"append",
"(",
"dep",
")",
"return",
"[",
"dict",
"(",
"t",
")",
"for",
"t",
"in",
"{",
"tuple",
"(",
"d",
".",
"items",
"(",
")",
")",
"for",
"d",
"in",
"dest",
"}",
"]"
] | Get a list of final destinations for a stop. | [
"Get",
"a",
"list",
"of",
"final",
"destinations",
"for",
"a",
"stop",
"."
] | 415d8b9c8bfd48caa82c1a1201bfd3beb670a117 | https://github.com/ludeeus/pyruter/blob/415d8b9c8bfd48caa82c1a1201bfd3beb670a117/pyruter/api.py#L55-L64 |
248,638 | cogniteev/docido-python-sdk | docido_sdk/toolbox/loader.py | resolve_name | def resolve_name(name, module=None):
"""Resolve a dotted name to a module and its parts. This is stolen
wholesale from unittest.TestLoader.loadTestByName.
"""
parts = name.split('.')
parts_copy = parts[:]
if module is None:
while parts_copy: # pragma: no cover
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
obj = getattr(obj, part)
return obj | python | def resolve_name(name, module=None):
"""Resolve a dotted name to a module and its parts. This is stolen
wholesale from unittest.TestLoader.loadTestByName.
"""
parts = name.split('.')
parts_copy = parts[:]
if module is None:
while parts_copy: # pragma: no cover
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[-1]
if not parts_copy:
raise
parts = parts[1:]
obj = module
for part in parts:
obj = getattr(obj, part)
return obj | [
"def",
"resolve_name",
"(",
"name",
",",
"module",
"=",
"None",
")",
":",
"parts",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"parts_copy",
"=",
"parts",
"[",
":",
"]",
"if",
"module",
"is",
"None",
":",
"while",
"parts_copy",
":",
"# pragma: no cover",
"try",
":",
"module",
"=",
"__import__",
"(",
"'.'",
".",
"join",
"(",
"parts_copy",
")",
")",
"break",
"except",
"ImportError",
":",
"del",
"parts_copy",
"[",
"-",
"1",
"]",
"if",
"not",
"parts_copy",
":",
"raise",
"parts",
"=",
"parts",
"[",
"1",
":",
"]",
"obj",
"=",
"module",
"for",
"part",
"in",
"parts",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"part",
")",
"return",
"obj"
] | Resolve a dotted name to a module and its parts. This is stolen
wholesale from unittest.TestLoader.loadTestByName. | [
"Resolve",
"a",
"dotted",
"name",
"to",
"a",
"module",
"and",
"its",
"parts",
".",
"This",
"is",
"stolen",
"wholesale",
"from",
"unittest",
".",
"TestLoader",
".",
"loadTestByName",
"."
] | 58ecb6c6f5757fd40c0601657ab18368da7ddf33 | https://github.com/cogniteev/docido-python-sdk/blob/58ecb6c6f5757fd40c0601657ab18368da7ddf33/docido_sdk/toolbox/loader.py#L2-L21 |
248,639 | django-xxx/django-mobi2 | mobi2/decorators.py | detect_mobile | def detect_mobile(view):
"""View Decorator that adds a "mobile" attribute to the request which is
True or False depending on whether the request should be considered
to come from a small-screen device such as a phone or a PDA"""
@wraps(view)
def detected(request, *args, **kwargs):
MobileDetectionMiddleware.process_request(request)
return view(request, *args, **kwargs)
detected.__doc__ = '%s\n[Wrapped by detect_mobile which detects if the request is from a phone]' % view.__doc__
return detected | python | def detect_mobile(view):
"""View Decorator that adds a "mobile" attribute to the request which is
True or False depending on whether the request should be considered
to come from a small-screen device such as a phone or a PDA"""
@wraps(view)
def detected(request, *args, **kwargs):
MobileDetectionMiddleware.process_request(request)
return view(request, *args, **kwargs)
detected.__doc__ = '%s\n[Wrapped by detect_mobile which detects if the request is from a phone]' % view.__doc__
return detected | [
"def",
"detect_mobile",
"(",
"view",
")",
":",
"@",
"wraps",
"(",
"view",
")",
"def",
"detected",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"MobileDetectionMiddleware",
".",
"process_request",
"(",
"request",
")",
"return",
"view",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"detected",
".",
"__doc__",
"=",
"'%s\\n[Wrapped by detect_mobile which detects if the request is from a phone]'",
"%",
"view",
".",
"__doc__",
"return",
"detected"
] | View Decorator that adds a "mobile" attribute to the request which is
True or False depending on whether the request should be considered
to come from a small-screen device such as a phone or a PDA | [
"View",
"Decorator",
"that",
"adds",
"a",
"mobile",
"attribute",
"to",
"the",
"request",
"which",
"is",
"True",
"or",
"False",
"depending",
"on",
"whether",
"the",
"request",
"should",
"be",
"considered",
"to",
"come",
"from",
"a",
"small",
"-",
"screen",
"device",
"such",
"as",
"a",
"phone",
"or",
"a",
"PDA"
] | 7ac323faa1a9599f3cd39acd3c49626819ce0538 | https://github.com/django-xxx/django-mobi2/blob/7ac323faa1a9599f3cd39acd3c49626819ce0538/mobi2/decorators.py#L8-L18 |
248,640 | tomnor/channelpack | channelpack/datautils.py | masked | def masked(a, b):
"""Return a numpy array with values from a where elements in b are
not False. Populate with numpy.nan where b is False. When plotting,
those elements look like missing, which can be a desired result.
"""
if np.any([a.dtype.kind.startswith(c) for c in ['i', 'u', 'f', 'c']]):
n = np.array([np.nan for i in range(len(a))])
else:
n = np.array([None for i in range(len(a))])
# a = a.astype(object)
return np.where(b, a, n) | python | def masked(a, b):
"""Return a numpy array with values from a where elements in b are
not False. Populate with numpy.nan where b is False. When plotting,
those elements look like missing, which can be a desired result.
"""
if np.any([a.dtype.kind.startswith(c) for c in ['i', 'u', 'f', 'c']]):
n = np.array([np.nan for i in range(len(a))])
else:
n = np.array([None for i in range(len(a))])
# a = a.astype(object)
return np.where(b, a, n) | [
"def",
"masked",
"(",
"a",
",",
"b",
")",
":",
"if",
"np",
".",
"any",
"(",
"[",
"a",
".",
"dtype",
".",
"kind",
".",
"startswith",
"(",
"c",
")",
"for",
"c",
"in",
"[",
"'i'",
",",
"'u'",
",",
"'f'",
",",
"'c'",
"]",
"]",
")",
":",
"n",
"=",
"np",
".",
"array",
"(",
"[",
"np",
".",
"nan",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
")",
"]",
")",
"else",
":",
"n",
"=",
"np",
".",
"array",
"(",
"[",
"None",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"a",
")",
")",
"]",
")",
"# a = a.astype(object)",
"return",
"np",
".",
"where",
"(",
"b",
",",
"a",
",",
"n",
")"
] | Return a numpy array with values from a where elements in b are
not False. Populate with numpy.nan where b is False. When plotting,
those elements look like missing, which can be a desired result. | [
"Return",
"a",
"numpy",
"array",
"with",
"values",
"from",
"a",
"where",
"elements",
"in",
"b",
"are",
"not",
"False",
".",
"Populate",
"with",
"numpy",
".",
"nan",
"where",
"b",
"is",
"False",
".",
"When",
"plotting",
"those",
"elements",
"look",
"like",
"missing",
"which",
"can",
"be",
"a",
"desired",
"result",
"."
] | 9ad3cd11c698aed4c0fc178385b2ba38a7d0efae | https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/datautils.py#L16-L28 |
248,641 | tomnor/channelpack | channelpack/datautils.py | duration_bool | def duration_bool(b, rule, samplerate=None):
"""
Mask the parts in b being True but does not meet the duration
rules. Return an updated copy of b.
b: 1d array with True or False elements.
rule: str
The rule including the string 'dur' to be evaled.
samplerate: None or float
Has an effect on the result.
For each part of b that is True, a variable ``dur`` is set to the
count of elements, or the result of (len(part) / samplerate). And then
eval is called on the rule.
"""
if rule is None:
return b
slicelst = slicelist(b)
b2 = np.array(b)
if samplerate is None:
samplerate = 1.0
for sc in slicelst:
dur = (sc.stop - sc.start) / samplerate # NOQA
if not eval(rule):
b2[sc] = False
return b2 | python | def duration_bool(b, rule, samplerate=None):
"""
Mask the parts in b being True but does not meet the duration
rules. Return an updated copy of b.
b: 1d array with True or False elements.
rule: str
The rule including the string 'dur' to be evaled.
samplerate: None or float
Has an effect on the result.
For each part of b that is True, a variable ``dur`` is set to the
count of elements, or the result of (len(part) / samplerate). And then
eval is called on the rule.
"""
if rule is None:
return b
slicelst = slicelist(b)
b2 = np.array(b)
if samplerate is None:
samplerate = 1.0
for sc in slicelst:
dur = (sc.stop - sc.start) / samplerate # NOQA
if not eval(rule):
b2[sc] = False
return b2 | [
"def",
"duration_bool",
"(",
"b",
",",
"rule",
",",
"samplerate",
"=",
"None",
")",
":",
"if",
"rule",
"is",
"None",
":",
"return",
"b",
"slicelst",
"=",
"slicelist",
"(",
"b",
")",
"b2",
"=",
"np",
".",
"array",
"(",
"b",
")",
"if",
"samplerate",
"is",
"None",
":",
"samplerate",
"=",
"1.0",
"for",
"sc",
"in",
"slicelst",
":",
"dur",
"=",
"(",
"sc",
".",
"stop",
"-",
"sc",
".",
"start",
")",
"/",
"samplerate",
"# NOQA",
"if",
"not",
"eval",
"(",
"rule",
")",
":",
"b2",
"[",
"sc",
"]",
"=",
"False",
"return",
"b2"
] | Mask the parts in b being True but does not meet the duration
rules. Return an updated copy of b.
b: 1d array with True or False elements.
rule: str
The rule including the string 'dur' to be evaled.
samplerate: None or float
Has an effect on the result.
For each part of b that is True, a variable ``dur`` is set to the
count of elements, or the result of (len(part) / samplerate). And then
eval is called on the rule. | [
"Mask",
"the",
"parts",
"in",
"b",
"being",
"True",
"but",
"does",
"not",
"meet",
"the",
"duration",
"rules",
".",
"Return",
"an",
"updated",
"copy",
"of",
"b",
"."
] | 9ad3cd11c698aed4c0fc178385b2ba38a7d0efae | https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/datautils.py#L31-L63 |
248,642 | tomnor/channelpack | channelpack/datautils.py | startstop_bool | def startstop_bool(pack):
"""Make a bool array based on start and stop conditions.
pack:
pack.ChannelPack instance
If there is start conditions but no stop conditions, this is legal,
the True section will begin at first start and remain the rest of
the array. Likewise, if there is stop conditions but no start
condition, the returned array will be all True until the first stop
slice, and the rest of the array is set to False.
"""
b_TRUE = np.ones(pack.rec_cnt) == True # NOQA
start_list = pack.conconf.conditions_list('startcond')
stop_list = pack.conconf.conditions_list('stopcond')
# Pre-check:
runflag = 'startstop'
if not start_list and not stop_list:
return b_TRUE
elif not start_list:
runflag = 'stoponly'
elif not stop_list:
runflag = 'start_only'
# startb:
if runflag == 'stoponly':
# all False (dummy assignment)
startb = b_TRUE == False # NOQA
else:
startb = b_TRUE
for cond in start_list:
startb = startb & pack._mask_array(cond)
# stopb:
if runflag == 'startonly':
# all False (dummy assignment)
stopb = b_TRUE == False # NOQA
else:
stopb = b_TRUE
for cond in stop_list:
stopb = stopb & pack._mask_array(cond)
stopextend = pack.conconf.get_stopextend()
return _startstop_bool(startb, stopb, runflag, stopextend) | python | def startstop_bool(pack):
"""Make a bool array based on start and stop conditions.
pack:
pack.ChannelPack instance
If there is start conditions but no stop conditions, this is legal,
the True section will begin at first start and remain the rest of
the array. Likewise, if there is stop conditions but no start
condition, the returned array will be all True until the first stop
slice, and the rest of the array is set to False.
"""
b_TRUE = np.ones(pack.rec_cnt) == True # NOQA
start_list = pack.conconf.conditions_list('startcond')
stop_list = pack.conconf.conditions_list('stopcond')
# Pre-check:
runflag = 'startstop'
if not start_list and not stop_list:
return b_TRUE
elif not start_list:
runflag = 'stoponly'
elif not stop_list:
runflag = 'start_only'
# startb:
if runflag == 'stoponly':
# all False (dummy assignment)
startb = b_TRUE == False # NOQA
else:
startb = b_TRUE
for cond in start_list:
startb = startb & pack._mask_array(cond)
# stopb:
if runflag == 'startonly':
# all False (dummy assignment)
stopb = b_TRUE == False # NOQA
else:
stopb = b_TRUE
for cond in stop_list:
stopb = stopb & pack._mask_array(cond)
stopextend = pack.conconf.get_stopextend()
return _startstop_bool(startb, stopb, runflag, stopextend) | [
"def",
"startstop_bool",
"(",
"pack",
")",
":",
"b_TRUE",
"=",
"np",
".",
"ones",
"(",
"pack",
".",
"rec_cnt",
")",
"==",
"True",
"# NOQA",
"start_list",
"=",
"pack",
".",
"conconf",
".",
"conditions_list",
"(",
"'startcond'",
")",
"stop_list",
"=",
"pack",
".",
"conconf",
".",
"conditions_list",
"(",
"'stopcond'",
")",
"# Pre-check:",
"runflag",
"=",
"'startstop'",
"if",
"not",
"start_list",
"and",
"not",
"stop_list",
":",
"return",
"b_TRUE",
"elif",
"not",
"start_list",
":",
"runflag",
"=",
"'stoponly'",
"elif",
"not",
"stop_list",
":",
"runflag",
"=",
"'start_only'",
"# startb:",
"if",
"runflag",
"==",
"'stoponly'",
":",
"# all False (dummy assignment)",
"startb",
"=",
"b_TRUE",
"==",
"False",
"# NOQA",
"else",
":",
"startb",
"=",
"b_TRUE",
"for",
"cond",
"in",
"start_list",
":",
"startb",
"=",
"startb",
"&",
"pack",
".",
"_mask_array",
"(",
"cond",
")",
"# stopb:",
"if",
"runflag",
"==",
"'startonly'",
":",
"# all False (dummy assignment)",
"stopb",
"=",
"b_TRUE",
"==",
"False",
"# NOQA",
"else",
":",
"stopb",
"=",
"b_TRUE",
"for",
"cond",
"in",
"stop_list",
":",
"stopb",
"=",
"stopb",
"&",
"pack",
".",
"_mask_array",
"(",
"cond",
")",
"stopextend",
"=",
"pack",
".",
"conconf",
".",
"get_stopextend",
"(",
")",
"return",
"_startstop_bool",
"(",
"startb",
",",
"stopb",
",",
"runflag",
",",
"stopextend",
")"
] | Make a bool array based on start and stop conditions.
pack:
pack.ChannelPack instance
If there is start conditions but no stop conditions, this is legal,
the True section will begin at first start and remain the rest of
the array. Likewise, if there is stop conditions but no start
condition, the returned array will be all True until the first stop
slice, and the rest of the array is set to False. | [
"Make",
"a",
"bool",
"array",
"based",
"on",
"start",
"and",
"stop",
"conditions",
"."
] | 9ad3cd11c698aed4c0fc178385b2ba38a7d0efae | https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/datautils.py#L66-L113 |
248,643 | tomnor/channelpack | channelpack/datautils.py | _startstop_bool | def _startstop_bool(startb, stopb, runflag, stopextend):
"""Return boolean array based on start and stop conditions.
startb, stopb: Numpy 1D arrays of the same length.
Boolean arrays for start and stop conditions being fullfilled or not.
"""
# All false at start
res = np.zeros(len(startb)) == True # NOQA
start_slices = slicelist(startb)
stop_slices = slicelist(stopb)
# Special case when there is a start but no stop slice or vice versa:
# if start_slices and not stop_slices:
if runflag == 'startonly':
try:
start = start_slices[0]
# Make True from first start and rest of array.
res[start.start:] = True
return res
except IndexError:
# Only start specified but no start condition
# fullfilled. Return all False.
return res
elif runflag == 'stoponly':
try:
stop = stop_slices[0]
res[:stop.start + stopextend] = True # Make True up to first stop.
return res
except IndexError:
# Only stop specified but no stop condition fullfilled
# Return all True
return res == False # NOQA
stop = slice(0, 0) # For first check
start = slice(0, 0) # For a possibly empty list start_slices.
for start in start_slices:
if start.start < stop.start:
continue
for stop in stop_slices:
if stop.start > start.start:
res[start.start: stop.start + stopextend] = True
break # Next start
else:
# On a given start slice, the entire list of stop slices was
# exhausted, none being later than the given start. It must mean
# that from this given start, the rest is to be True:
break
# There was no stop for the last start in loop
if start.start > stop.start:
res[start.start:] = True
return res | python | def _startstop_bool(startb, stopb, runflag, stopextend):
"""Return boolean array based on start and stop conditions.
startb, stopb: Numpy 1D arrays of the same length.
Boolean arrays for start and stop conditions being fullfilled or not.
"""
# All false at start
res = np.zeros(len(startb)) == True # NOQA
start_slices = slicelist(startb)
stop_slices = slicelist(stopb)
# Special case when there is a start but no stop slice or vice versa:
# if start_slices and not stop_slices:
if runflag == 'startonly':
try:
start = start_slices[0]
# Make True from first start and rest of array.
res[start.start:] = True
return res
except IndexError:
# Only start specified but no start condition
# fullfilled. Return all False.
return res
elif runflag == 'stoponly':
try:
stop = stop_slices[0]
res[:stop.start + stopextend] = True # Make True up to first stop.
return res
except IndexError:
# Only stop specified but no stop condition fullfilled
# Return all True
return res == False # NOQA
stop = slice(0, 0) # For first check
start = slice(0, 0) # For a possibly empty list start_slices.
for start in start_slices:
if start.start < stop.start:
continue
for stop in stop_slices:
if stop.start > start.start:
res[start.start: stop.start + stopextend] = True
break # Next start
else:
# On a given start slice, the entire list of stop slices was
# exhausted, none being later than the given start. It must mean
# that from this given start, the rest is to be True:
break
# There was no stop for the last start in loop
if start.start > stop.start:
res[start.start:] = True
return res | [
"def",
"_startstop_bool",
"(",
"startb",
",",
"stopb",
",",
"runflag",
",",
"stopextend",
")",
":",
"# All false at start",
"res",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"startb",
")",
")",
"==",
"True",
"# NOQA",
"start_slices",
"=",
"slicelist",
"(",
"startb",
")",
"stop_slices",
"=",
"slicelist",
"(",
"stopb",
")",
"# Special case when there is a start but no stop slice or vice versa:",
"# if start_slices and not stop_slices:",
"if",
"runflag",
"==",
"'startonly'",
":",
"try",
":",
"start",
"=",
"start_slices",
"[",
"0",
"]",
"# Make True from first start and rest of array.",
"res",
"[",
"start",
".",
"start",
":",
"]",
"=",
"True",
"return",
"res",
"except",
"IndexError",
":",
"# Only start specified but no start condition",
"# fullfilled. Return all False.",
"return",
"res",
"elif",
"runflag",
"==",
"'stoponly'",
":",
"try",
":",
"stop",
"=",
"stop_slices",
"[",
"0",
"]",
"res",
"[",
":",
"stop",
".",
"start",
"+",
"stopextend",
"]",
"=",
"True",
"# Make True up to first stop.",
"return",
"res",
"except",
"IndexError",
":",
"# Only stop specified but no stop condition fullfilled",
"# Return all True",
"return",
"res",
"==",
"False",
"# NOQA",
"stop",
"=",
"slice",
"(",
"0",
",",
"0",
")",
"# For first check",
"start",
"=",
"slice",
"(",
"0",
",",
"0",
")",
"# For a possibly empty list start_slices.",
"for",
"start",
"in",
"start_slices",
":",
"if",
"start",
".",
"start",
"<",
"stop",
".",
"start",
":",
"continue",
"for",
"stop",
"in",
"stop_slices",
":",
"if",
"stop",
".",
"start",
">",
"start",
".",
"start",
":",
"res",
"[",
"start",
".",
"start",
":",
"stop",
".",
"start",
"+",
"stopextend",
"]",
"=",
"True",
"break",
"# Next start",
"else",
":",
"# On a given start slice, the entire list of stop slices was",
"# exhausted, none being later than the given start. It must mean",
"# that from this given start, the rest is to be True:",
"break",
"# There was no stop for the last start in loop",
"if",
"start",
".",
"start",
">",
"stop",
".",
"start",
":",
"res",
"[",
"start",
".",
"start",
":",
"]",
"=",
"True",
"return",
"res"
] | Return boolean array based on start and stop conditions.
startb, stopb: Numpy 1D arrays of the same length.
Boolean arrays for start and stop conditions being fullfilled or not. | [
"Return",
"boolean",
"array",
"based",
"on",
"start",
"and",
"stop",
"conditions",
"."
] | 9ad3cd11c698aed4c0fc178385b2ba38a7d0efae | https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/datautils.py#L116-L171 |
248,644 | tomnor/channelpack | channelpack/datautils.py | slicelist | def slicelist(b):
"""Produce a list of slices given the boolean array b.
Start and stop in each slice describe the True sections in b."""
slicelst = []
started = False
for i, e in enumerate(b):
if e and not started:
start = i
started = True
elif not e and started:
slicelst.append(slice(start, i))
started = False
if e:
slicelst.append(slice(start, i + 1)) # True in the end.
return slicelst | python | def slicelist(b):
"""Produce a list of slices given the boolean array b.
Start and stop in each slice describe the True sections in b."""
slicelst = []
started = False
for i, e in enumerate(b):
if e and not started:
start = i
started = True
elif not e and started:
slicelst.append(slice(start, i))
started = False
if e:
slicelst.append(slice(start, i + 1)) # True in the end.
return slicelst | [
"def",
"slicelist",
"(",
"b",
")",
":",
"slicelst",
"=",
"[",
"]",
"started",
"=",
"False",
"for",
"i",
",",
"e",
"in",
"enumerate",
"(",
"b",
")",
":",
"if",
"e",
"and",
"not",
"started",
":",
"start",
"=",
"i",
"started",
"=",
"True",
"elif",
"not",
"e",
"and",
"started",
":",
"slicelst",
".",
"append",
"(",
"slice",
"(",
"start",
",",
"i",
")",
")",
"started",
"=",
"False",
"if",
"e",
":",
"slicelst",
".",
"append",
"(",
"slice",
"(",
"start",
",",
"i",
"+",
"1",
")",
")",
"# True in the end.",
"return",
"slicelst"
] | Produce a list of slices given the boolean array b.
Start and stop in each slice describe the True sections in b. | [
"Produce",
"a",
"list",
"of",
"slices",
"given",
"the",
"boolean",
"array",
"b",
"."
] | 9ad3cd11c698aed4c0fc178385b2ba38a7d0efae | https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/datautils.py#L174-L192 |
248,645 | edeposit/edeposit.amqp.storage | src/edeposit/amqp/storage/archive_storage.py | save_archive | def save_archive(archive):
"""
Save `archive` into database and into proper indexes.
Attr:
archive (obj): Instance of the :class:`.DBArchive`.
Returns:
obj: :class:`.DBArchive` without data.
Raises:
InvalidType: When the `archive` is not instance of :class:`.DBArchive`.
UnindexablePublication: When there is no index (property) which can be
used to index `archive` in database.
"""
_assert_obj_type(archive, obj_type=DBArchive)
_get_handler().store_object(archive)
return archive.to_comm(light_request=True) | python | def save_archive(archive):
"""
Save `archive` into database and into proper indexes.
Attr:
archive (obj): Instance of the :class:`.DBArchive`.
Returns:
obj: :class:`.DBArchive` without data.
Raises:
InvalidType: When the `archive` is not instance of :class:`.DBArchive`.
UnindexablePublication: When there is no index (property) which can be
used to index `archive` in database.
"""
_assert_obj_type(archive, obj_type=DBArchive)
_get_handler().store_object(archive)
return archive.to_comm(light_request=True) | [
"def",
"save_archive",
"(",
"archive",
")",
":",
"_assert_obj_type",
"(",
"archive",
",",
"obj_type",
"=",
"DBArchive",
")",
"_get_handler",
"(",
")",
".",
"store_object",
"(",
"archive",
")",
"return",
"archive",
".",
"to_comm",
"(",
"light_request",
"=",
"True",
")"
] | Save `archive` into database and into proper indexes.
Attr:
archive (obj): Instance of the :class:`.DBArchive`.
Returns:
obj: :class:`.DBArchive` without data.
Raises:
InvalidType: When the `archive` is not instance of :class:`.DBArchive`.
UnindexablePublication: When there is no index (property) which can be
used to index `archive` in database. | [
"Save",
"archive",
"into",
"database",
"and",
"into",
"proper",
"indexes",
"."
] | fb6bd326249847de04b17b64e856c878665cea92 | https://github.com/edeposit/edeposit.amqp.storage/blob/fb6bd326249847de04b17b64e856c878665cea92/src/edeposit/amqp/storage/archive_storage.py#L29-L48 |
248,646 | rorr73/LifeSOSpy | lifesospy/__main__.py | main | def main(argv):
"""
Basic command line script for testing library.
"""
# Parse command line arguments
parser = argparse.ArgumentParser(
description="LifeSOSpy v{} - {}".format(
PROJECT_VERSION, PROJECT_DESCRIPTION))
parser.add_argument(
'-H', '--host',
help="Hostname/IP Address for the LifeSOS server, if we are to run as a client.",
default=None)
parser.add_argument(
'-P', '--port',
help="TCP port for the LifeSOS ethernet interface.",
default=str(BaseUnit.TCP_PORT))
parser.add_argument(
'-p', '--password',
help="Password for the Master user, if remote access requires it.",
default='')
parser.add_argument(
'-v', '--verbose',
help="Display all logging output.",
action='store_true')
args = parser.parse_args()
# Configure logger
logging.basicConfig(
format="%(asctime)s %(levelname)-5s (%(threadName)s) [%(name)s] %(message)s",
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.DEBUG if args.verbose else logging.INFO)
# Create base unit instance and start up interface
print("LifeSOSpy v{} - {}\n".format(PROJECT_VERSION, PROJECT_DESCRIPTION))
loop = asyncio.get_event_loop()
baseunit = BaseUnit(args.host, args.port)
if args.password:
baseunit.password = args.password
baseunit.start()
# Provide interactive prompt for running test commands on another thread
loop.run_until_complete(
loop.run_in_executor(
None, _handle_interactive_baseunit_tests, baseunit, loop))
# Shut down interface and event loop
baseunit.stop()
loop.close() | python | def main(argv):
"""
Basic command line script for testing library.
"""
# Parse command line arguments
parser = argparse.ArgumentParser(
description="LifeSOSpy v{} - {}".format(
PROJECT_VERSION, PROJECT_DESCRIPTION))
parser.add_argument(
'-H', '--host',
help="Hostname/IP Address for the LifeSOS server, if we are to run as a client.",
default=None)
parser.add_argument(
'-P', '--port',
help="TCP port for the LifeSOS ethernet interface.",
default=str(BaseUnit.TCP_PORT))
parser.add_argument(
'-p', '--password',
help="Password for the Master user, if remote access requires it.",
default='')
parser.add_argument(
'-v', '--verbose',
help="Display all logging output.",
action='store_true')
args = parser.parse_args()
# Configure logger
logging.basicConfig(
format="%(asctime)s %(levelname)-5s (%(threadName)s) [%(name)s] %(message)s",
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.DEBUG if args.verbose else logging.INFO)
# Create base unit instance and start up interface
print("LifeSOSpy v{} - {}\n".format(PROJECT_VERSION, PROJECT_DESCRIPTION))
loop = asyncio.get_event_loop()
baseunit = BaseUnit(args.host, args.port)
if args.password:
baseunit.password = args.password
baseunit.start()
# Provide interactive prompt for running test commands on another thread
loop.run_until_complete(
loop.run_in_executor(
None, _handle_interactive_baseunit_tests, baseunit, loop))
# Shut down interface and event loop
baseunit.stop()
loop.close() | [
"def",
"main",
"(",
"argv",
")",
":",
"# Parse command line arguments",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"LifeSOSpy v{} - {}\"",
".",
"format",
"(",
"PROJECT_VERSION",
",",
"PROJECT_DESCRIPTION",
")",
")",
"parser",
".",
"add_argument",
"(",
"'-H'",
",",
"'--host'",
",",
"help",
"=",
"\"Hostname/IP Address for the LifeSOS server, if we are to run as a client.\"",
",",
"default",
"=",
"None",
")",
"parser",
".",
"add_argument",
"(",
"'-P'",
",",
"'--port'",
",",
"help",
"=",
"\"TCP port for the LifeSOS ethernet interface.\"",
",",
"default",
"=",
"str",
"(",
"BaseUnit",
".",
"TCP_PORT",
")",
")",
"parser",
".",
"add_argument",
"(",
"'-p'",
",",
"'--password'",
",",
"help",
"=",
"\"Password for the Master user, if remote access requires it.\"",
",",
"default",
"=",
"''",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"help",
"=",
"\"Display all logging output.\"",
",",
"action",
"=",
"'store_true'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"# Configure logger",
"logging",
".",
"basicConfig",
"(",
"format",
"=",
"\"%(asctime)s %(levelname)-5s (%(threadName)s) [%(name)s] %(message)s\"",
",",
"datefmt",
"=",
"'%Y-%m-%d %H:%M:%S'",
",",
"level",
"=",
"logging",
".",
"DEBUG",
"if",
"args",
".",
"verbose",
"else",
"logging",
".",
"INFO",
")",
"# Create base unit instance and start up interface",
"print",
"(",
"\"LifeSOSpy v{} - {}\\n\"",
".",
"format",
"(",
"PROJECT_VERSION",
",",
"PROJECT_DESCRIPTION",
")",
")",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"baseunit",
"=",
"BaseUnit",
"(",
"args",
".",
"host",
",",
"args",
".",
"port",
")",
"if",
"args",
".",
"password",
":",
"baseunit",
".",
"password",
"=",
"args",
".",
"password",
"baseunit",
".",
"start",
"(",
")",
"# Provide interactive prompt for running test commands on another thread",
"loop",
".",
"run_until_complete",
"(",
"loop",
".",
"run_in_executor",
"(",
"None",
",",
"_handle_interactive_baseunit_tests",
",",
"baseunit",
",",
"loop",
")",
")",
"# Shut down interface and event loop",
"baseunit",
".",
"stop",
"(",
")",
"loop",
".",
"close",
"(",
")"
] | Basic command line script for testing library. | [
"Basic",
"command",
"line",
"script",
"for",
"testing",
"library",
"."
] | 62360fbab2e90bf04d52b547093bdab2d4e389b4 | https://github.com/rorr73/LifeSOSpy/blob/62360fbab2e90bf04d52b547093bdab2d4e389b4/lifesospy/__main__.py#L23-L71 |
248,647 | laysakura/relshell | relshell/timestamp.py | Timestamp.datetime | def datetime(self):
"""Return `datetime` object"""
return dt.datetime(
self.year(), self.month(), self.day(),
self.hour(), self.minute(), self.second(),
int(self.millisecond() * 1e3)) | python | def datetime(self):
"""Return `datetime` object"""
return dt.datetime(
self.year(), self.month(), self.day(),
self.hour(), self.minute(), self.second(),
int(self.millisecond() * 1e3)) | [
"def",
"datetime",
"(",
"self",
")",
":",
"return",
"dt",
".",
"datetime",
"(",
"self",
".",
"year",
"(",
")",
",",
"self",
".",
"month",
"(",
")",
",",
"self",
".",
"day",
"(",
")",
",",
"self",
".",
"hour",
"(",
")",
",",
"self",
".",
"minute",
"(",
")",
",",
"self",
".",
"second",
"(",
")",
",",
"int",
"(",
"self",
".",
"millisecond",
"(",
")",
"*",
"1e3",
")",
")"
] | Return `datetime` object | [
"Return",
"datetime",
"object"
] | 9ca5c03a34c11cb763a4a75595f18bf4383aa8cc | https://github.com/laysakura/relshell/blob/9ca5c03a34c11cb763a4a75595f18bf4383aa8cc/relshell/timestamp.py#L63-L68 |
248,648 | malthe/pop | src/pop/control.py | CommandConfiguration.get_command | def get_command(self, name):
"""Wrap command class in constructor."""
def command(options):
client = ZookeeperClient(
"%s:%d" % (options.pop('host'), options.pop('port')),
session_timeout=1000
)
path = options.pop('path_prefix')
force = options.pop('force')
extra = options.pop('extra')
# Apply settings to options dictionary. While this does
# conflate arguments for the utility with command options,
# that's something we're willing to accept.
options.update(extra)
controller = Command(client, path, self.services, force)
method = getattr(controller, "cmd_%s" % name)
return method(**options)
return command | python | def get_command(self, name):
"""Wrap command class in constructor."""
def command(options):
client = ZookeeperClient(
"%s:%d" % (options.pop('host'), options.pop('port')),
session_timeout=1000
)
path = options.pop('path_prefix')
force = options.pop('force')
extra = options.pop('extra')
# Apply settings to options dictionary. While this does
# conflate arguments for the utility with command options,
# that's something we're willing to accept.
options.update(extra)
controller = Command(client, path, self.services, force)
method = getattr(controller, "cmd_%s" % name)
return method(**options)
return command | [
"def",
"get_command",
"(",
"self",
",",
"name",
")",
":",
"def",
"command",
"(",
"options",
")",
":",
"client",
"=",
"ZookeeperClient",
"(",
"\"%s:%d\"",
"%",
"(",
"options",
".",
"pop",
"(",
"'host'",
")",
",",
"options",
".",
"pop",
"(",
"'port'",
")",
")",
",",
"session_timeout",
"=",
"1000",
")",
"path",
"=",
"options",
".",
"pop",
"(",
"'path_prefix'",
")",
"force",
"=",
"options",
".",
"pop",
"(",
"'force'",
")",
"extra",
"=",
"options",
".",
"pop",
"(",
"'extra'",
")",
"# Apply settings to options dictionary. While this does",
"# conflate arguments for the utility with command options,",
"# that's something we're willing to accept.",
"options",
".",
"update",
"(",
"extra",
")",
"controller",
"=",
"Command",
"(",
"client",
",",
"path",
",",
"self",
".",
"services",
",",
"force",
")",
"method",
"=",
"getattr",
"(",
"controller",
",",
"\"cmd_%s\"",
"%",
"name",
")",
"return",
"method",
"(",
"*",
"*",
"options",
")",
"return",
"command"
] | Wrap command class in constructor. | [
"Wrap",
"command",
"class",
"in",
"constructor",
"."
] | 3b58b91b41d8b9bee546eb40dc280a57500b8bed | https://github.com/malthe/pop/blob/3b58b91b41d8b9bee546eb40dc280a57500b8bed/src/pop/control.py#L61-L83 |
248,649 | naphatkrit/easyci | easyci/version.py | get_installed_version | def get_installed_version(vcs):
"""Get the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
str - version number
Raises:
VersionNotInstalledError
"""
version_path = _get_version_path(vcs)
if not os.path.exists(version_path):
raise VersionNotInstalledError
with open(version_path, 'r') as f:
return f.read().strip() | python | def get_installed_version(vcs):
"""Get the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
str - version number
Raises:
VersionNotInstalledError
"""
version_path = _get_version_path(vcs)
if not os.path.exists(version_path):
raise VersionNotInstalledError
with open(version_path, 'r') as f:
return f.read().strip() | [
"def",
"get_installed_version",
"(",
"vcs",
")",
":",
"version_path",
"=",
"_get_version_path",
"(",
"vcs",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"version_path",
")",
":",
"raise",
"VersionNotInstalledError",
"with",
"open",
"(",
"version_path",
",",
"'r'",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")"
] | Get the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
str - version number
Raises:
VersionNotInstalledError | [
"Get",
"the",
"installed",
"version",
"for",
"this",
"project",
"."
] | 7aee8d7694fe4e2da42ce35b0f700bc840c8b95f | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/version.py#L12-L28 |
248,650 | naphatkrit/easyci | easyci/version.py | set_installed_version | def set_installed_version(vcs, version):
"""Set the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
version (str)
"""
version_path = _get_version_path(vcs)
with open(version_path, 'w') as f:
f.write(version) | python | def set_installed_version(vcs, version):
"""Set the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
version (str)
"""
version_path = _get_version_path(vcs)
with open(version_path, 'w') as f:
f.write(version) | [
"def",
"set_installed_version",
"(",
"vcs",
",",
"version",
")",
":",
"version_path",
"=",
"_get_version_path",
"(",
"vcs",
")",
"with",
"open",
"(",
"version_path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"version",
")"
] | Set the installed version for this project.
Args:
vcs (easyci.vcs.base.Vcs)
version (str) | [
"Set",
"the",
"installed",
"version",
"for",
"this",
"project",
"."
] | 7aee8d7694fe4e2da42ce35b0f700bc840c8b95f | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/version.py#L31-L40 |
248,651 | minhhoit/yacms | yacms/core/sitemaps.py | DisplayableSitemap.get_urls | def get_urls(self, **kwargs):
"""
Ensure the correct host by injecting the current site.
"""
kwargs["site"] = Site.objects.get(id=current_site_id())
return super(DisplayableSitemap, self).get_urls(**kwargs) | python | def get_urls(self, **kwargs):
"""
Ensure the correct host by injecting the current site.
"""
kwargs["site"] = Site.objects.get(id=current_site_id())
return super(DisplayableSitemap, self).get_urls(**kwargs) | [
"def",
"get_urls",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"\"site\"",
"]",
"=",
"Site",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"current_site_id",
"(",
")",
")",
"return",
"super",
"(",
"DisplayableSitemap",
",",
"self",
")",
".",
"get_urls",
"(",
"*",
"*",
"kwargs",
")"
] | Ensure the correct host by injecting the current site. | [
"Ensure",
"the",
"correct",
"host",
"by",
"injecting",
"the",
"current",
"site",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/sitemaps.py#L33-L38 |
248,652 | dossier/dossier.web | dossier/extraction/usernames.py | usernames | def usernames(urls):
'''Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list.
'''
usernames = StringCounter()
for url, count in urls.items():
uparse = urlparse(url)
path = uparse.path
hostname = uparse.hostname
m = username_re.match(path)
if m:
usernames[m.group('username')] += count
elif hostname in ['twitter.com', 'www.facebook.com']:
usernames[path.lstrip('/')] += count
return usernames | python | def usernames(urls):
'''Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list.
'''
usernames = StringCounter()
for url, count in urls.items():
uparse = urlparse(url)
path = uparse.path
hostname = uparse.hostname
m = username_re.match(path)
if m:
usernames[m.group('username')] += count
elif hostname in ['twitter.com', 'www.facebook.com']:
usernames[path.lstrip('/')] += count
return usernames | [
"def",
"usernames",
"(",
"urls",
")",
":",
"usernames",
"=",
"StringCounter",
"(",
")",
"for",
"url",
",",
"count",
"in",
"urls",
".",
"items",
"(",
")",
":",
"uparse",
"=",
"urlparse",
"(",
"url",
")",
"path",
"=",
"uparse",
".",
"path",
"hostname",
"=",
"uparse",
".",
"hostname",
"m",
"=",
"username_re",
".",
"match",
"(",
"path",
")",
"if",
"m",
":",
"usernames",
"[",
"m",
".",
"group",
"(",
"'username'",
")",
"]",
"+=",
"count",
"elif",
"hostname",
"in",
"[",
"'twitter.com'",
",",
"'www.facebook.com'",
"]",
":",
"usernames",
"[",
"path",
".",
"lstrip",
"(",
"'/'",
")",
"]",
"+=",
"count",
"return",
"usernames"
] | Take an iterable of `urls` of normalized URL or file paths and
attempt to extract usernames. Returns a list. | [
"Take",
"an",
"iterable",
"of",
"urls",
"of",
"normalized",
"URL",
"or",
"file",
"paths",
"and",
"attempt",
"to",
"extract",
"usernames",
".",
"Returns",
"a",
"list",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/extraction/usernames.py#L15-L30 |
248,653 | PSU-OIT-ARC/elasticmodels | elasticmodels/forms.py | BaseSearchForm.cleaned_data | def cleaned_data(self):
"""
When cleaned_data is initially accessed, we want to ensure the form
gets validated which has the side effect of setting cleaned_data to
something.
"""
if not hasattr(self, "_cleaned_data"):
self._cleaned_data = {}
self.is_valid()
return self._cleaned_data | python | def cleaned_data(self):
"""
When cleaned_data is initially accessed, we want to ensure the form
gets validated which has the side effect of setting cleaned_data to
something.
"""
if not hasattr(self, "_cleaned_data"):
self._cleaned_data = {}
self.is_valid()
return self._cleaned_data | [
"def",
"cleaned_data",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_cleaned_data\"",
")",
":",
"self",
".",
"_cleaned_data",
"=",
"{",
"}",
"self",
".",
"is_valid",
"(",
")",
"return",
"self",
".",
"_cleaned_data"
] | When cleaned_data is initially accessed, we want to ensure the form
gets validated which has the side effect of setting cleaned_data to
something. | [
"When",
"cleaned_data",
"is",
"initially",
"accessed",
"we",
"want",
"to",
"ensure",
"the",
"form",
"gets",
"validated",
"which",
"has",
"the",
"side",
"effect",
"of",
"setting",
"cleaned_data",
"to",
"something",
"."
] | 67870508096f66123ef10b89789bbac06571cc80 | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/forms.py#L32-L41 |
248,654 | PSU-OIT-ARC/elasticmodels | elasticmodels/forms.py | BaseSearchForm.search | def search(self):
"""
This should return an elasticsearch-DSL Search instance, list or
queryset based on the values in self.cleaned_data.
"""
results = self.index.objects.all()
# reduce the results based on the q field
if self.cleaned_data.get("q"):
results = results.query(
"multi_match",
query=self.cleaned_data['q'],
fields=self.get_fields(),
# this prevents ES from erroring out when a string is used on a
# number field (for example)
lenient=True
)
return results | python | def search(self):
"""
This should return an elasticsearch-DSL Search instance, list or
queryset based on the values in self.cleaned_data.
"""
results = self.index.objects.all()
# reduce the results based on the q field
if self.cleaned_data.get("q"):
results = results.query(
"multi_match",
query=self.cleaned_data['q'],
fields=self.get_fields(),
# this prevents ES from erroring out when a string is used on a
# number field (for example)
lenient=True
)
return results | [
"def",
"search",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"index",
".",
"objects",
".",
"all",
"(",
")",
"# reduce the results based on the q field",
"if",
"self",
".",
"cleaned_data",
".",
"get",
"(",
"\"q\"",
")",
":",
"results",
"=",
"results",
".",
"query",
"(",
"\"multi_match\"",
",",
"query",
"=",
"self",
".",
"cleaned_data",
"[",
"'q'",
"]",
",",
"fields",
"=",
"self",
".",
"get_fields",
"(",
")",
",",
"# this prevents ES from erroring out when a string is used on a",
"# number field (for example)",
"lenient",
"=",
"True",
")",
"return",
"results"
] | This should return an elasticsearch-DSL Search instance, list or
queryset based on the values in self.cleaned_data. | [
"This",
"should",
"return",
"an",
"elasticsearch",
"-",
"DSL",
"Search",
"instance",
"list",
"or",
"queryset",
"based",
"on",
"the",
"values",
"in",
"self",
".",
"cleaned_data",
"."
] | 67870508096f66123ef10b89789bbac06571cc80 | https://github.com/PSU-OIT-ARC/elasticmodels/blob/67870508096f66123ef10b89789bbac06571cc80/elasticmodels/forms.py#L62-L79 |
248,655 | quasipedia/simpleactors | simpleactors.py | on | def on(message):
'''Decorator that register a class method as callback for a message.'''
def decorator(function):
try:
function._callback_messages.append(message)
except AttributeError:
function._callback_messages = [message]
return function
return decorator | python | def on(message):
'''Decorator that register a class method as callback for a message.'''
def decorator(function):
try:
function._callback_messages.append(message)
except AttributeError:
function._callback_messages = [message]
return function
return decorator | [
"def",
"on",
"(",
"message",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"try",
":",
"function",
".",
"_callback_messages",
".",
"append",
"(",
"message",
")",
"except",
"AttributeError",
":",
"function",
".",
"_callback_messages",
"=",
"[",
"message",
"]",
"return",
"function",
"return",
"decorator"
] | Decorator that register a class method as callback for a message. | [
"Decorator",
"that",
"register",
"a",
"class",
"method",
"as",
"callback",
"for",
"a",
"message",
"."
] | 4253da2d10b3df080b5e7b3fbee03aa6dd10db07 | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L43-L51 |
248,656 | quasipedia/simpleactors | simpleactors.py | Actor.plug | def plug(self):
'''Add the actor's methods to the callback registry.'''
if self.__plugged:
return
for _, method in inspect.getmembers(self, predicate=inspect.ismethod):
if hasattr(method, '_callback_messages'):
for message in method._callback_messages:
global_callbacks[message].add(method)
self.__plugged = True | python | def plug(self):
'''Add the actor's methods to the callback registry.'''
if self.__plugged:
return
for _, method in inspect.getmembers(self, predicate=inspect.ismethod):
if hasattr(method, '_callback_messages'):
for message in method._callback_messages:
global_callbacks[message].add(method)
self.__plugged = True | [
"def",
"plug",
"(",
"self",
")",
":",
"if",
"self",
".",
"__plugged",
":",
"return",
"for",
"_",
",",
"method",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
",",
"predicate",
"=",
"inspect",
".",
"ismethod",
")",
":",
"if",
"hasattr",
"(",
"method",
",",
"'_callback_messages'",
")",
":",
"for",
"message",
"in",
"method",
".",
"_callback_messages",
":",
"global_callbacks",
"[",
"message",
"]",
".",
"add",
"(",
"method",
")",
"self",
".",
"__plugged",
"=",
"True"
] | Add the actor's methods to the callback registry. | [
"Add",
"the",
"actor",
"s",
"methods",
"to",
"the",
"callback",
"registry",
"."
] | 4253da2d10b3df080b5e7b3fbee03aa6dd10db07 | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L74-L82 |
248,657 | quasipedia/simpleactors | simpleactors.py | Actor.unplug | def unplug(self):
'''Remove the actor's methods from the callback registry.'''
if not self.__plugged:
return
members = set([method for _, method
in inspect.getmembers(self, predicate=inspect.ismethod)])
for message in global_callbacks:
global_callbacks[message] -= members
self.__plugged = False | python | def unplug(self):
'''Remove the actor's methods from the callback registry.'''
if not self.__plugged:
return
members = set([method for _, method
in inspect.getmembers(self, predicate=inspect.ismethod)])
for message in global_callbacks:
global_callbacks[message] -= members
self.__plugged = False | [
"def",
"unplug",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__plugged",
":",
"return",
"members",
"=",
"set",
"(",
"[",
"method",
"for",
"_",
",",
"method",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
",",
"predicate",
"=",
"inspect",
".",
"ismethod",
")",
"]",
")",
"for",
"message",
"in",
"global_callbacks",
":",
"global_callbacks",
"[",
"message",
"]",
"-=",
"members",
"self",
".",
"__plugged",
"=",
"False"
] | Remove the actor's methods from the callback registry. | [
"Remove",
"the",
"actor",
"s",
"methods",
"from",
"the",
"callback",
"registry",
"."
] | 4253da2d10b3df080b5e7b3fbee03aa6dd10db07 | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L84-L92 |
248,658 | quasipedia/simpleactors | simpleactors.py | Director.run | def run(self):
'''Run until there are no events to be processed.'''
# We left-append rather than emit (right-append) because some message
# may have been already queued for execution before the director runs.
global_event_queue.appendleft((INITIATE, self, (), {}))
while global_event_queue:
self.process_event(global_event_queue.popleft()) | python | def run(self):
'''Run until there are no events to be processed.'''
# We left-append rather than emit (right-append) because some message
# may have been already queued for execution before the director runs.
global_event_queue.appendleft((INITIATE, self, (), {}))
while global_event_queue:
self.process_event(global_event_queue.popleft()) | [
"def",
"run",
"(",
"self",
")",
":",
"# We left-append rather than emit (right-append) because some message",
"# may have been already queued for execution before the director runs.",
"global_event_queue",
".",
"appendleft",
"(",
"(",
"INITIATE",
",",
"self",
",",
"(",
")",
",",
"{",
"}",
")",
")",
"while",
"global_event_queue",
":",
"self",
".",
"process_event",
"(",
"global_event_queue",
".",
"popleft",
"(",
")",
")"
] | Run until there are no events to be processed. | [
"Run",
"until",
"there",
"are",
"no",
"events",
"to",
"be",
"processed",
"."
] | 4253da2d10b3df080b5e7b3fbee03aa6dd10db07 | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L115-L121 |
248,659 | quasipedia/simpleactors | simpleactors.py | Director.halt | def halt(self, message, emitter, *args, **kwargs):
'''Halt the execution of the loop.'''
self.process_event((FINISH, self, (), {}))
global_event_queue.clear() | python | def halt(self, message, emitter, *args, **kwargs):
'''Halt the execution of the loop.'''
self.process_event((FINISH, self, (), {}))
global_event_queue.clear() | [
"def",
"halt",
"(",
"self",
",",
"message",
",",
"emitter",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"process_event",
"(",
"(",
"FINISH",
",",
"self",
",",
"(",
")",
",",
"{",
"}",
")",
")",
"global_event_queue",
".",
"clear",
"(",
")"
] | Halt the execution of the loop. | [
"Halt",
"the",
"execution",
"of",
"the",
"loop",
"."
] | 4253da2d10b3df080b5e7b3fbee03aa6dd10db07 | https://github.com/quasipedia/simpleactors/blob/4253da2d10b3df080b5e7b3fbee03aa6dd10db07/simpleactors.py#L135-L138 |
248,660 | dossier/dossier.web | dossier/web/builder.py | create_injector | def create_injector(param_name, fun_param_value):
'''Dependency injection with Bottle.
This creates a simple dependency injector that will map
``param_name`` in routes to the value ``fun_param_value()``
each time the route is invoked.
``fun_param_value`` is a closure so that it is lazily evaluated.
This is useful for handling thread local services like database
connections.
:param str param_name: name of function parameter to inject into
:param fun_param_value: the value to insert
:type fun_param_value: a closure that can be applied with zero
arguments
'''
class _(object):
api = 2
def apply(self, callback, route):
if param_name not in inspect.getargspec(route.callback)[0]:
return callback
def _(*args, **kwargs):
pval = fun_param_value()
if pval is None:
logger.error('service "%s" unavailable', param_name)
bottle.abort(503, 'service "%s" unavailable' % param_name)
return
kwargs[param_name] = pval
return callback(*args, **kwargs)
return _
return _() | python | def create_injector(param_name, fun_param_value):
'''Dependency injection with Bottle.
This creates a simple dependency injector that will map
``param_name`` in routes to the value ``fun_param_value()``
each time the route is invoked.
``fun_param_value`` is a closure so that it is lazily evaluated.
This is useful for handling thread local services like database
connections.
:param str param_name: name of function parameter to inject into
:param fun_param_value: the value to insert
:type fun_param_value: a closure that can be applied with zero
arguments
'''
class _(object):
api = 2
def apply(self, callback, route):
if param_name not in inspect.getargspec(route.callback)[0]:
return callback
def _(*args, **kwargs):
pval = fun_param_value()
if pval is None:
logger.error('service "%s" unavailable', param_name)
bottle.abort(503, 'service "%s" unavailable' % param_name)
return
kwargs[param_name] = pval
return callback(*args, **kwargs)
return _
return _() | [
"def",
"create_injector",
"(",
"param_name",
",",
"fun_param_value",
")",
":",
"class",
"_",
"(",
"object",
")",
":",
"api",
"=",
"2",
"def",
"apply",
"(",
"self",
",",
"callback",
",",
"route",
")",
":",
"if",
"param_name",
"not",
"in",
"inspect",
".",
"getargspec",
"(",
"route",
".",
"callback",
")",
"[",
"0",
"]",
":",
"return",
"callback",
"def",
"_",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pval",
"=",
"fun_param_value",
"(",
")",
"if",
"pval",
"is",
"None",
":",
"logger",
".",
"error",
"(",
"'service \"%s\" unavailable'",
",",
"param_name",
")",
"bottle",
".",
"abort",
"(",
"503",
",",
"'service \"%s\" unavailable'",
"%",
"param_name",
")",
"return",
"kwargs",
"[",
"param_name",
"]",
"=",
"pval",
"return",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"_",
"return",
"_",
"(",
")"
] | Dependency injection with Bottle.
This creates a simple dependency injector that will map
``param_name`` in routes to the value ``fun_param_value()``
each time the route is invoked.
``fun_param_value`` is a closure so that it is lazily evaluated.
This is useful for handling thread local services like database
connections.
:param str param_name: name of function parameter to inject into
:param fun_param_value: the value to insert
:type fun_param_value: a closure that can be applied with zero
arguments | [
"Dependency",
"injection",
"with",
"Bottle",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L295-L327 |
248,661 | dossier/dossier.web | dossier/web/builder.py | WebBuilder.get_app | def get_app(self):
'''Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle`
'''
if self.config is None:
# If the user never sets a config instance, then just create
# a default.
self.config = Config()
if self.mount_prefix is None:
self.mount_prefix = self.config.config.get('url_prefix')
self.inject('config', lambda: self.config)
self.inject('kvlclient', lambda: self.config.kvlclient)
self.inject('store', lambda: self.config.store)
self.inject('label_store', lambda: self.config.label_store)
self.inject('tags', lambda: self.config.tags)
self.inject('search_engines', lambda: self.search_engines)
self.inject('filters', lambda: self.filters)
self.inject('request', lambda: bottle.request)
self.inject('response', lambda: bottle.response)
# DEPRECATED. Remove. ---AG
self.inject('visid_to_dbid', lambda: self.visid_to_dbid)
self.inject('dbid_to_visid', lambda: self.dbid_to_visid)
# Also DEPRECATED.
self.inject('label_hooks', lambda: [])
# Load routes defined in entry points.
for extroute in self.config.config.get('external_routes', []):
mod, fun_name = extroute.split(':')
logger.info('Loading external route: %s', extroute)
fun = getattr(__import__(mod, fromlist=[fun_name]), fun_name)
self.add_routes(fun())
# This adds the `json=True` feature on routes, which always coerces
# the output to JSON. Bottle, by default, only permits dictionaries
# to be JSON, which is the correct behavior. (Because returning JSON
# arrays is a hazard.)
#
# So we should fix the routes and then remove this. ---AG
self.app.install(JsonPlugin())
# Throw away the app and return it. Because this is elimination!
app = self.app
self.app = None
if self.mount_prefix is not None:
root = bottle.Bottle()
root.mount(self.mount_prefix, app)
return root
else:
return app | python | def get_app(self):
'''Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle`
'''
if self.config is None:
# If the user never sets a config instance, then just create
# a default.
self.config = Config()
if self.mount_prefix is None:
self.mount_prefix = self.config.config.get('url_prefix')
self.inject('config', lambda: self.config)
self.inject('kvlclient', lambda: self.config.kvlclient)
self.inject('store', lambda: self.config.store)
self.inject('label_store', lambda: self.config.label_store)
self.inject('tags', lambda: self.config.tags)
self.inject('search_engines', lambda: self.search_engines)
self.inject('filters', lambda: self.filters)
self.inject('request', lambda: bottle.request)
self.inject('response', lambda: bottle.response)
# DEPRECATED. Remove. ---AG
self.inject('visid_to_dbid', lambda: self.visid_to_dbid)
self.inject('dbid_to_visid', lambda: self.dbid_to_visid)
# Also DEPRECATED.
self.inject('label_hooks', lambda: [])
# Load routes defined in entry points.
for extroute in self.config.config.get('external_routes', []):
mod, fun_name = extroute.split(':')
logger.info('Loading external route: %s', extroute)
fun = getattr(__import__(mod, fromlist=[fun_name]), fun_name)
self.add_routes(fun())
# This adds the `json=True` feature on routes, which always coerces
# the output to JSON. Bottle, by default, only permits dictionaries
# to be JSON, which is the correct behavior. (Because returning JSON
# arrays is a hazard.)
#
# So we should fix the routes and then remove this. ---AG
self.app.install(JsonPlugin())
# Throw away the app and return it. Because this is elimination!
app = self.app
self.app = None
if self.mount_prefix is not None:
root = bottle.Bottle()
root.mount(self.mount_prefix, app)
return root
else:
return app | [
"def",
"get_app",
"(",
"self",
")",
":",
"if",
"self",
".",
"config",
"is",
"None",
":",
"# If the user never sets a config instance, then just create",
"# a default.",
"self",
".",
"config",
"=",
"Config",
"(",
")",
"if",
"self",
".",
"mount_prefix",
"is",
"None",
":",
"self",
".",
"mount_prefix",
"=",
"self",
".",
"config",
".",
"config",
".",
"get",
"(",
"'url_prefix'",
")",
"self",
".",
"inject",
"(",
"'config'",
",",
"lambda",
":",
"self",
".",
"config",
")",
"self",
".",
"inject",
"(",
"'kvlclient'",
",",
"lambda",
":",
"self",
".",
"config",
".",
"kvlclient",
")",
"self",
".",
"inject",
"(",
"'store'",
",",
"lambda",
":",
"self",
".",
"config",
".",
"store",
")",
"self",
".",
"inject",
"(",
"'label_store'",
",",
"lambda",
":",
"self",
".",
"config",
".",
"label_store",
")",
"self",
".",
"inject",
"(",
"'tags'",
",",
"lambda",
":",
"self",
".",
"config",
".",
"tags",
")",
"self",
".",
"inject",
"(",
"'search_engines'",
",",
"lambda",
":",
"self",
".",
"search_engines",
")",
"self",
".",
"inject",
"(",
"'filters'",
",",
"lambda",
":",
"self",
".",
"filters",
")",
"self",
".",
"inject",
"(",
"'request'",
",",
"lambda",
":",
"bottle",
".",
"request",
")",
"self",
".",
"inject",
"(",
"'response'",
",",
"lambda",
":",
"bottle",
".",
"response",
")",
"# DEPRECATED. Remove. ---AG",
"self",
".",
"inject",
"(",
"'visid_to_dbid'",
",",
"lambda",
":",
"self",
".",
"visid_to_dbid",
")",
"self",
".",
"inject",
"(",
"'dbid_to_visid'",
",",
"lambda",
":",
"self",
".",
"dbid_to_visid",
")",
"# Also DEPRECATED.",
"self",
".",
"inject",
"(",
"'label_hooks'",
",",
"lambda",
":",
"[",
"]",
")",
"# Load routes defined in entry points.",
"for",
"extroute",
"in",
"self",
".",
"config",
".",
"config",
".",
"get",
"(",
"'external_routes'",
",",
"[",
"]",
")",
":",
"mod",
",",
"fun_name",
"=",
"extroute",
".",
"split",
"(",
"':'",
")",
"logger",
".",
"info",
"(",
"'Loading external route: %s'",
",",
"extroute",
")",
"fun",
"=",
"getattr",
"(",
"__import__",
"(",
"mod",
",",
"fromlist",
"=",
"[",
"fun_name",
"]",
")",
",",
"fun_name",
")",
"self",
".",
"add_routes",
"(",
"fun",
"(",
")",
")",
"# This adds the `json=True` feature on routes, which always coerces",
"# the output to JSON. Bottle, by default, only permits dictionaries",
"# to be JSON, which is the correct behavior. (Because returning JSON",
"# arrays is a hazard.)",
"#",
"# So we should fix the routes and then remove this. ---AG",
"self",
".",
"app",
".",
"install",
"(",
"JsonPlugin",
"(",
")",
")",
"# Throw away the app and return it. Because this is elimination!",
"app",
"=",
"self",
".",
"app",
"self",
".",
"app",
"=",
"None",
"if",
"self",
".",
"mount_prefix",
"is",
"not",
"None",
":",
"root",
"=",
"bottle",
".",
"Bottle",
"(",
")",
"root",
".",
"mount",
"(",
"self",
".",
"mount_prefix",
",",
"app",
")",
"return",
"root",
"else",
":",
"return",
"app"
] | Eliminate the builder by producing a new Bottle application.
This should be the final call in your method chain. It uses all
of the built up options to create a new Bottle application.
:rtype: :class:`bottle.Bottle` | [
"Eliminate",
"the",
"builder",
"by",
"producing",
"a",
"new",
"Bottle",
"application",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L81-L136 |
248,662 | dossier/dossier.web | dossier/web/builder.py | WebBuilder.add_search_engine | def add_search_engine(self, name, engine):
'''Adds a search engine with the given name.
``engine`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.SearchEngine`, which should provide a means
of obtaining recommendations given a query.
The ``engine`` must be a class so that its dependencies can be
injected when the corresponding route is executed by the user.
If ``engine`` is ``None``, then it removes a possibly existing
search engine named ``name``.
:param str name: The name of the search engine. This appears
in the list of search engines provided to the
user, and is how the search engine is invoked
via REST.
:param engine: A search engine *class*.
:type engine: `type`
:rtype: :class:`WebBuilder`
'''
if engine is None:
self.search_engines.pop(name, None)
self.search_engines[name] = engine
return self | python | def add_search_engine(self, name, engine):
'''Adds a search engine with the given name.
``engine`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.SearchEngine`, which should provide a means
of obtaining recommendations given a query.
The ``engine`` must be a class so that its dependencies can be
injected when the corresponding route is executed by the user.
If ``engine`` is ``None``, then it removes a possibly existing
search engine named ``name``.
:param str name: The name of the search engine. This appears
in the list of search engines provided to the
user, and is how the search engine is invoked
via REST.
:param engine: A search engine *class*.
:type engine: `type`
:rtype: :class:`WebBuilder`
'''
if engine is None:
self.search_engines.pop(name, None)
self.search_engines[name] = engine
return self | [
"def",
"add_search_engine",
"(",
"self",
",",
"name",
",",
"engine",
")",
":",
"if",
"engine",
"is",
"None",
":",
"self",
".",
"search_engines",
".",
"pop",
"(",
"name",
",",
"None",
")",
"self",
".",
"search_engines",
"[",
"name",
"]",
"=",
"engine",
"return",
"self"
] | Adds a search engine with the given name.
``engine`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.SearchEngine`, which should provide a means
of obtaining recommendations given a query.
The ``engine`` must be a class so that its dependencies can be
injected when the corresponding route is executed by the user.
If ``engine`` is ``None``, then it removes a possibly existing
search engine named ``name``.
:param str name: The name of the search engine. This appears
in the list of search engines provided to the
user, and is how the search engine is invoked
via REST.
:param engine: A search engine *class*.
:type engine: `type`
:rtype: :class:`WebBuilder` | [
"Adds",
"a",
"search",
"engine",
"with",
"the",
"given",
"name",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L164-L189 |
248,663 | dossier/dossier.web | dossier/web/builder.py | WebBuilder.add_filter | def add_filter(self, name, filter):
'''Adds a filter with the given name.
``filter`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.Filter`, which should provide a means
of creating a predicate function.
The ``filter`` must be a class so that its dependencies can be
injected when the corresponding route is executed by the user.
If ``filter`` is ``None``, then it removes a possibly existing
filter named ``name``.
:param str name: The name of the filter. This is how the search engine
is invoked via REST.
:param engine: A filter *class*.
:type engine: `type`
:rtype: :class:`WebBuilder`
'''
if name is None:
self.filters.pop(name, None)
self.filters[name] = filter
return self | python | def add_filter(self, name, filter):
'''Adds a filter with the given name.
``filter`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.Filter`, which should provide a means
of creating a predicate function.
The ``filter`` must be a class so that its dependencies can be
injected when the corresponding route is executed by the user.
If ``filter`` is ``None``, then it removes a possibly existing
filter named ``name``.
:param str name: The name of the filter. This is how the search engine
is invoked via REST.
:param engine: A filter *class*.
:type engine: `type`
:rtype: :class:`WebBuilder`
'''
if name is None:
self.filters.pop(name, None)
self.filters[name] = filter
return self | [
"def",
"add_filter",
"(",
"self",
",",
"name",
",",
"filter",
")",
":",
"if",
"name",
"is",
"None",
":",
"self",
".",
"filters",
".",
"pop",
"(",
"name",
",",
"None",
")",
"self",
".",
"filters",
"[",
"name",
"]",
"=",
"filter",
"return",
"self"
] | Adds a filter with the given name.
``filter`` must be the **class** object rather than
an instance. The class *must* be a subclass of
:class:`dossier.web.Filter`, which should provide a means
of creating a predicate function.
The ``filter`` must be a class so that its dependencies can be
injected when the corresponding route is executed by the user.
If ``filter`` is ``None``, then it removes a possibly existing
filter named ``name``.
:param str name: The name of the filter. This is how the search engine
is invoked via REST.
:param engine: A filter *class*.
:type engine: `type`
:rtype: :class:`WebBuilder` | [
"Adds",
"a",
"filter",
"with",
"the",
"given",
"name",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L191-L214 |
248,664 | dossier/dossier.web | dossier/web/builder.py | WebBuilder.add_routes | def add_routes(self, routes):
'''Merges a Bottle application into this one.
:param routes: A Bottle application or a sequence of routes.
:type routes: :class:`bottle.Bottle` or `[bottle route]`.
:rtype: :class:`WebBuilder`
'''
# Basically the same as `self.app.merge(routes)`, except this
# changes the owner of the route so that plugins on `self.app`
# apply to the routes given here.
if isinstance(routes, bottle.Bottle):
routes = routes.routes
for route in routes:
route.app = self.app
self.app.add_route(route)
return self | python | def add_routes(self, routes):
'''Merges a Bottle application into this one.
:param routes: A Bottle application or a sequence of routes.
:type routes: :class:`bottle.Bottle` or `[bottle route]`.
:rtype: :class:`WebBuilder`
'''
# Basically the same as `self.app.merge(routes)`, except this
# changes the owner of the route so that plugins on `self.app`
# apply to the routes given here.
if isinstance(routes, bottle.Bottle):
routes = routes.routes
for route in routes:
route.app = self.app
self.app.add_route(route)
return self | [
"def",
"add_routes",
"(",
"self",
",",
"routes",
")",
":",
"# Basically the same as `self.app.merge(routes)`, except this",
"# changes the owner of the route so that plugins on `self.app`",
"# apply to the routes given here.",
"if",
"isinstance",
"(",
"routes",
",",
"bottle",
".",
"Bottle",
")",
":",
"routes",
"=",
"routes",
".",
"routes",
"for",
"route",
"in",
"routes",
":",
"route",
".",
"app",
"=",
"self",
".",
"app",
"self",
".",
"app",
".",
"add_route",
"(",
"route",
")",
"return",
"self"
] | Merges a Bottle application into this one.
:param routes: A Bottle application or a sequence of routes.
:type routes: :class:`bottle.Bottle` or `[bottle route]`.
:rtype: :class:`WebBuilder` | [
"Merges",
"a",
"Bottle",
"application",
"into",
"this",
"one",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L216-L231 |
248,665 | dossier/dossier.web | dossier/web/builder.py | WebBuilder.enable_cors | def enable_cors(self):
'''Enables Cross Origin Resource Sharing.
This makes sure the necessary headers are set so that this
web application's routes can be accessed from other origins.
:rtype: :class:`WebBuilder`
'''
def access_control_headers():
bottle.response.headers['Access-Control-Allow-Origin'] = '*'
bottle.response.headers['Access-Control-Allow-Methods'] = \
'GET, POST, PUT, DELETE, OPTIONS'
bottle.response.headers['Access-Control-Allow-Headers'] = \
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
def options_response(res):
if bottle.request.method == 'OPTIONS':
new_res = bottle.HTTPResponse()
new_res.headers['Access-Control-Allow-Origin'] = '*'
new_res.headers['Access-Control-Allow-Methods'] = \
bottle.request.headers.get(
'Access-Control-Request-Method', '')
new_res.headers['Access-Control-Allow-Headers'] = \
bottle.request.headers.get(
'Access-Control-Request-Headers', '')
return new_res
res.headers['Allow'] += ', OPTIONS'
return bottle.request.app.default_error_handler(res)
self.app.add_hook('after_request', access_control_headers)
self.app.error_handler[int(405)] = options_response
return self | python | def enable_cors(self):
'''Enables Cross Origin Resource Sharing.
This makes sure the necessary headers are set so that this
web application's routes can be accessed from other origins.
:rtype: :class:`WebBuilder`
'''
def access_control_headers():
bottle.response.headers['Access-Control-Allow-Origin'] = '*'
bottle.response.headers['Access-Control-Allow-Methods'] = \
'GET, POST, PUT, DELETE, OPTIONS'
bottle.response.headers['Access-Control-Allow-Headers'] = \
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
def options_response(res):
if bottle.request.method == 'OPTIONS':
new_res = bottle.HTTPResponse()
new_res.headers['Access-Control-Allow-Origin'] = '*'
new_res.headers['Access-Control-Allow-Methods'] = \
bottle.request.headers.get(
'Access-Control-Request-Method', '')
new_res.headers['Access-Control-Allow-Headers'] = \
bottle.request.headers.get(
'Access-Control-Request-Headers', '')
return new_res
res.headers['Allow'] += ', OPTIONS'
return bottle.request.app.default_error_handler(res)
self.app.add_hook('after_request', access_control_headers)
self.app.error_handler[int(405)] = options_response
return self | [
"def",
"enable_cors",
"(",
"self",
")",
":",
"def",
"access_control_headers",
"(",
")",
":",
"bottle",
".",
"response",
".",
"headers",
"[",
"'Access-Control-Allow-Origin'",
"]",
"=",
"'*'",
"bottle",
".",
"response",
".",
"headers",
"[",
"'Access-Control-Allow-Methods'",
"]",
"=",
"'GET, POST, PUT, DELETE, OPTIONS'",
"bottle",
".",
"response",
".",
"headers",
"[",
"'Access-Control-Allow-Headers'",
"]",
"=",
"'Origin, X-Requested-With, Content-Type, Accept, Authorization'",
"def",
"options_response",
"(",
"res",
")",
":",
"if",
"bottle",
".",
"request",
".",
"method",
"==",
"'OPTIONS'",
":",
"new_res",
"=",
"bottle",
".",
"HTTPResponse",
"(",
")",
"new_res",
".",
"headers",
"[",
"'Access-Control-Allow-Origin'",
"]",
"=",
"'*'",
"new_res",
".",
"headers",
"[",
"'Access-Control-Allow-Methods'",
"]",
"=",
"bottle",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Access-Control-Request-Method'",
",",
"''",
")",
"new_res",
".",
"headers",
"[",
"'Access-Control-Allow-Headers'",
"]",
"=",
"bottle",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Access-Control-Request-Headers'",
",",
"''",
")",
"return",
"new_res",
"res",
".",
"headers",
"[",
"'Allow'",
"]",
"+=",
"', OPTIONS'",
"return",
"bottle",
".",
"request",
".",
"app",
".",
"default_error_handler",
"(",
"res",
")",
"self",
".",
"app",
".",
"add_hook",
"(",
"'after_request'",
",",
"access_control_headers",
")",
"self",
".",
"app",
".",
"error_handler",
"[",
"int",
"(",
"405",
")",
"]",
"=",
"options_response",
"return",
"self"
] | Enables Cross Origin Resource Sharing.
This makes sure the necessary headers are set so that this
web application's routes can be accessed from other origins.
:rtype: :class:`WebBuilder` | [
"Enables",
"Cross",
"Origin",
"Resource",
"Sharing",
"."
] | 1cad1cce3c37d3a4e956abc710a2bc1afe16a092 | https://github.com/dossier/dossier.web/blob/1cad1cce3c37d3a4e956abc710a2bc1afe16a092/dossier/web/builder.py#L251-L282 |
248,666 | pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.init_properties | def init_properties(self) -> 'PygalleBaseClass':
""" Initialize the Pigalle properties.
# Returns:
PygalleBaseClass: The current instance.
"""
self._pigalle = {
PygalleBaseClass.__KEYS.INTERNALS: dict(),
PygalleBaseClass.__KEYS.PUBLIC: dict()
}
return self | python | def init_properties(self) -> 'PygalleBaseClass':
""" Initialize the Pigalle properties.
# Returns:
PygalleBaseClass: The current instance.
"""
self._pigalle = {
PygalleBaseClass.__KEYS.INTERNALS: dict(),
PygalleBaseClass.__KEYS.PUBLIC: dict()
}
return self | [
"def",
"init_properties",
"(",
"self",
")",
"->",
"'PygalleBaseClass'",
":",
"self",
".",
"_pigalle",
"=",
"{",
"PygalleBaseClass",
".",
"__KEYS",
".",
"INTERNALS",
":",
"dict",
"(",
")",
",",
"PygalleBaseClass",
".",
"__KEYS",
".",
"PUBLIC",
":",
"dict",
"(",
")",
"}",
"return",
"self"
] | Initialize the Pigalle properties.
# Returns:
PygalleBaseClass: The current instance. | [
"Initialize",
"the",
"Pigalle",
"properties",
"."
] | fa683f7f88b63ca46a0970af81a558c9efbbe942 | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L66-L76 |
248,667 | pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.set | def set(self, key: str, value: Any) -> 'PygalleBaseClass':
""" Define a public property.
:param key:
:param value:
:return:
"""
self.public()[key] = value
return self | python | def set(self, key: str, value: Any) -> 'PygalleBaseClass':
""" Define a public property.
:param key:
:param value:
:return:
"""
self.public()[key] = value
return self | [
"def",
"set",
"(",
"self",
",",
"key",
":",
"str",
",",
"value",
":",
"Any",
")",
"->",
"'PygalleBaseClass'",
":",
"self",
".",
"public",
"(",
")",
"[",
"key",
"]",
"=",
"value",
"return",
"self"
] | Define a public property.
:param key:
:param value:
:return: | [
"Define",
"a",
"public",
"property",
"."
] | fa683f7f88b63ca46a0970af81a558c9efbbe942 | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L121-L129 |
248,668 | pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.set_category | def set_category(self, category: str = None) -> 'PygalleBaseClass':
""" Define the category of the class.
# Arguments
category: The name of category.
# Returns:
PygalleBaseClass: An instance of :class:`PygalleBaseClass`
"""
return self.set_internal(PygalleBaseClass.__KEYS.CATEGORY, category) | python | def set_category(self, category: str = None) -> 'PygalleBaseClass':
""" Define the category of the class.
# Arguments
category: The name of category.
# Returns:
PygalleBaseClass: An instance of :class:`PygalleBaseClass`
"""
return self.set_internal(PygalleBaseClass.__KEYS.CATEGORY, category) | [
"def",
"set_category",
"(",
"self",
",",
"category",
":",
"str",
"=",
"None",
")",
"->",
"'PygalleBaseClass'",
":",
"return",
"self",
".",
"set_internal",
"(",
"PygalleBaseClass",
".",
"__KEYS",
".",
"CATEGORY",
",",
"category",
")"
] | Define the category of the class.
# Arguments
category: The name of category.
# Returns:
PygalleBaseClass: An instance of :class:`PygalleBaseClass` | [
"Define",
"the",
"category",
"of",
"the",
"class",
"."
] | fa683f7f88b63ca46a0970af81a558c9efbbe942 | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L180-L189 |
248,669 | pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.instance_of | def instance_of(self, kls: Any) -> bool:
""" Return true if the current object is an instance of passed type.
# Arguments
kls: The class.
# Returns:
bool:
* Return true if the current object is an instance of passed type.
* False else.
"""
if not kls:
raise ValueError
return isinstance(self, kls) | python | def instance_of(self, kls: Any) -> bool:
""" Return true if the current object is an instance of passed type.
# Arguments
kls: The class.
# Returns:
bool:
* Return true if the current object is an instance of passed type.
* False else.
"""
if not kls:
raise ValueError
return isinstance(self, kls) | [
"def",
"instance_of",
"(",
"self",
",",
"kls",
":",
"Any",
")",
"->",
"bool",
":",
"if",
"not",
"kls",
":",
"raise",
"ValueError",
"return",
"isinstance",
"(",
"self",
",",
"kls",
")"
] | Return true if the current object is an instance of passed type.
# Arguments
kls: The class.
# Returns:
bool:
* Return true if the current object is an instance of passed type.
* False else. | [
"Return",
"true",
"if",
"the",
"current",
"object",
"is",
"an",
"instance",
"of",
"passed",
"type",
"."
] | fa683f7f88b63ca46a0970af81a558c9efbbe942 | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L245-L258 |
248,670 | pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.is_pigalle_class | def is_pigalle_class(kls: ClassVar) -> bool:
""" Return true if the passed object as argument is a class being to the Pigalle framework.
# Arguments
kls: The class to check.
# Returns:
bool:
* True if class is Pigalle.
* False else.
"""
return (kls is PygalleBaseClass) or (issubclass(type(kls), PygalleBaseClass)) | python | def is_pigalle_class(kls: ClassVar) -> bool:
""" Return true if the passed object as argument is a class being to the Pigalle framework.
# Arguments
kls: The class to check.
# Returns:
bool:
* True if class is Pigalle.
* False else.
"""
return (kls is PygalleBaseClass) or (issubclass(type(kls), PygalleBaseClass)) | [
"def",
"is_pigalle_class",
"(",
"kls",
":",
"ClassVar",
")",
"->",
"bool",
":",
"return",
"(",
"kls",
"is",
"PygalleBaseClass",
")",
"or",
"(",
"issubclass",
"(",
"type",
"(",
"kls",
")",
",",
"PygalleBaseClass",
")",
")"
] | Return true if the passed object as argument is a class being to the Pigalle framework.
# Arguments
kls: The class to check.
# Returns:
bool:
* True if class is Pigalle.
* False else. | [
"Return",
"true",
"if",
"the",
"passed",
"object",
"as",
"argument",
"is",
"a",
"class",
"being",
"to",
"the",
"Pigalle",
"framework",
"."
] | fa683f7f88b63ca46a0970af81a558c9efbbe942 | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L276-L287 |
248,671 | pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.is_pigalle | def is_pigalle(obj: Any) -> bool:
""" Return true if the passed object as argument is a class or an
instance of class being to the Pigalle framework.
# Arguments
obj: The class or object to test.
# Returns:
bool:
* True if class or object is Pigalle.
* False else.
"""
return PygalleBaseClass.is_pigalle_class(obj) or PygalleBaseClass.is_pigalle_instance(obj) | python | def is_pigalle(obj: Any) -> bool:
""" Return true if the passed object as argument is a class or an
instance of class being to the Pigalle framework.
# Arguments
obj: The class or object to test.
# Returns:
bool:
* True if class or object is Pigalle.
* False else.
"""
return PygalleBaseClass.is_pigalle_class(obj) or PygalleBaseClass.is_pigalle_instance(obj) | [
"def",
"is_pigalle",
"(",
"obj",
":",
"Any",
")",
"->",
"bool",
":",
"return",
"PygalleBaseClass",
".",
"is_pigalle_class",
"(",
"obj",
")",
"or",
"PygalleBaseClass",
".",
"is_pigalle_instance",
"(",
"obj",
")"
] | Return true if the passed object as argument is a class or an
instance of class being to the Pigalle framework.
# Arguments
obj: The class or object to test.
# Returns:
bool:
* True if class or object is Pigalle.
* False else. | [
"Return",
"true",
"if",
"the",
"passed",
"object",
"as",
"argument",
"is",
"a",
"class",
"or",
"an",
"instance",
"of",
"class",
"being",
"to",
"the",
"Pigalle",
"framework",
"."
] | fa683f7f88b63ca46a0970af81a558c9efbbe942 | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L290-L303 |
248,672 | pygalle-io/pygalle.core.base.klass | src/pygalle/core/base/klass/__init__.py | PygalleBaseClass.has_method | def has_method(self, key: str) -> bool:
""" Return if a method exists for the current instance.
# Arguments
key: The method name.
# Returns:
bool:
* True if the current instance has the provided method.
* False else.
"""
return hasattr(self.__class__, key) and callable(getattr(self.__class__, key)) | python | def has_method(self, key: str) -> bool:
""" Return if a method exists for the current instance.
# Arguments
key: The method name.
# Returns:
bool:
* True if the current instance has the provided method.
* False else.
"""
return hasattr(self.__class__, key) and callable(getattr(self.__class__, key)) | [
"def",
"has_method",
"(",
"self",
",",
"key",
":",
"str",
")",
"->",
"bool",
":",
"return",
"hasattr",
"(",
"self",
".",
"__class__",
",",
"key",
")",
"and",
"callable",
"(",
"getattr",
"(",
"self",
".",
"__class__",
",",
"key",
")",
")"
] | Return if a method exists for the current instance.
# Arguments
key: The method name.
# Returns:
bool:
* True if the current instance has the provided method.
* False else. | [
"Return",
"if",
"a",
"method",
"exists",
"for",
"the",
"current",
"instance",
"."
] | fa683f7f88b63ca46a0970af81a558c9efbbe942 | https://github.com/pygalle-io/pygalle.core.base.klass/blob/fa683f7f88b63ca46a0970af81a558c9efbbe942/src/pygalle/core/base/klass/__init__.py#L319-L331 |
248,673 | inspirehep/plotextractor | plotextractor/extractor.py | extract_context | def extract_context(tex_file, extracted_image_data):
"""Extract context.
Given a .tex file and a label name, this function will extract the text
before and after for all the references made to this label in the text.
The number of characters to extract before and after is configurable.
:param tex_file (list): path to .tex file
:param extracted_image_data ([(string, string, list), ...]):
a list of tuples of images matched to labels and captions from
this document.
:return extracted_image_data ([(string, string, list, list),
(string, string, list, list),...)]: the same list, but now containing
extracted contexts
"""
if os.path.isdir(tex_file) or not os.path.exists(tex_file):
return []
lines = "".join(get_lines_from_file(tex_file))
# Generate context for each image and its assoc. labels
for data in extracted_image_data:
context_list = []
# Generate a list of index tuples for all matches
indicies = [match.span()
for match in re.finditer(r"(\\(?:fig|ref)\{%s\})" %
(re.escape(data['label']),),
lines)]
for startindex, endindex in indicies:
# Retrive all lines before label until beginning of file
i = startindex - CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT
if i < 0:
text_before = lines[:startindex]
else:
text_before = lines[i:startindex]
context_before = get_context(text_before, backwards=True)
# Retrive all lines from label until end of file and get context
i = endindex + CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT
text_after = lines[endindex:i]
context_after = get_context(text_after)
context_list.append(
context_before + ' \\ref{' + data['label'] + '} ' +
context_after
)
data['contexts'] = context_list | python | def extract_context(tex_file, extracted_image_data):
"""Extract context.
Given a .tex file and a label name, this function will extract the text
before and after for all the references made to this label in the text.
The number of characters to extract before and after is configurable.
:param tex_file (list): path to .tex file
:param extracted_image_data ([(string, string, list), ...]):
a list of tuples of images matched to labels and captions from
this document.
:return extracted_image_data ([(string, string, list, list),
(string, string, list, list),...)]: the same list, but now containing
extracted contexts
"""
if os.path.isdir(tex_file) or not os.path.exists(tex_file):
return []
lines = "".join(get_lines_from_file(tex_file))
# Generate context for each image and its assoc. labels
for data in extracted_image_data:
context_list = []
# Generate a list of index tuples for all matches
indicies = [match.span()
for match in re.finditer(r"(\\(?:fig|ref)\{%s\})" %
(re.escape(data['label']),),
lines)]
for startindex, endindex in indicies:
# Retrive all lines before label until beginning of file
i = startindex - CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT
if i < 0:
text_before = lines[:startindex]
else:
text_before = lines[i:startindex]
context_before = get_context(text_before, backwards=True)
# Retrive all lines from label until end of file and get context
i = endindex + CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT
text_after = lines[endindex:i]
context_after = get_context(text_after)
context_list.append(
context_before + ' \\ref{' + data['label'] + '} ' +
context_after
)
data['contexts'] = context_list | [
"def",
"extract_context",
"(",
"tex_file",
",",
"extracted_image_data",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"tex_file",
")",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"tex_file",
")",
":",
"return",
"[",
"]",
"lines",
"=",
"\"\"",
".",
"join",
"(",
"get_lines_from_file",
"(",
"tex_file",
")",
")",
"# Generate context for each image and its assoc. labels",
"for",
"data",
"in",
"extracted_image_data",
":",
"context_list",
"=",
"[",
"]",
"# Generate a list of index tuples for all matches",
"indicies",
"=",
"[",
"match",
".",
"span",
"(",
")",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"r\"(\\\\(?:fig|ref)\\{%s\\})\"",
"%",
"(",
"re",
".",
"escape",
"(",
"data",
"[",
"'label'",
"]",
")",
",",
")",
",",
"lines",
")",
"]",
"for",
"startindex",
",",
"endindex",
"in",
"indicies",
":",
"# Retrive all lines before label until beginning of file",
"i",
"=",
"startindex",
"-",
"CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT",
"if",
"i",
"<",
"0",
":",
"text_before",
"=",
"lines",
"[",
":",
"startindex",
"]",
"else",
":",
"text_before",
"=",
"lines",
"[",
"i",
":",
"startindex",
"]",
"context_before",
"=",
"get_context",
"(",
"text_before",
",",
"backwards",
"=",
"True",
")",
"# Retrive all lines from label until end of file and get context",
"i",
"=",
"endindex",
"+",
"CFG_PLOTEXTRACTOR_CONTEXT_EXTRACT_LIMIT",
"text_after",
"=",
"lines",
"[",
"endindex",
":",
"i",
"]",
"context_after",
"=",
"get_context",
"(",
"text_after",
")",
"context_list",
".",
"append",
"(",
"context_before",
"+",
"' \\\\ref{'",
"+",
"data",
"[",
"'label'",
"]",
"+",
"'} '",
"+",
"context_after",
")",
"data",
"[",
"'contexts'",
"]",
"=",
"context_list"
] | Extract context.
Given a .tex file and a label name, this function will extract the text
before and after for all the references made to this label in the text.
The number of characters to extract before and after is configurable.
:param tex_file (list): path to .tex file
:param extracted_image_data ([(string, string, list), ...]):
a list of tuples of images matched to labels and captions from
this document.
:return extracted_image_data ([(string, string, list, list),
(string, string, list, list),...)]: the same list, but now containing
extracted contexts | [
"Extract",
"context",
"."
] | 12a65350fb9f32d496f9ea57908d9a2771b20474 | https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L118-L165 |
248,674 | inspirehep/plotextractor | plotextractor/extractor.py | intelligently_find_filenames | def intelligently_find_filenames(line, TeX=False, ext=False,
commas_okay=False):
"""Intelligently find filenames.
Find the filename in the line. We don't support all filenames! Just eps
and ps for now.
:param: line (string): the line we want to get a filename out of
:return: filename ([string, ...]): what is probably the name of the file(s)
"""
files_included = ['ERROR']
if commas_okay:
valid_for_filename = '\\s*[A-Za-z0-9\\-\\=\\+/\\\\_\\.,%#]+'
else:
valid_for_filename = '\\s*[A-Za-z0-9\\-\\=\\+/\\\\_\\.%#]+'
if ext:
valid_for_filename += '\.e*ps[texfi2]*'
if TeX:
valid_for_filename += '[\.latex]*'
file_inclusion = re.findall('=' + valid_for_filename + '[ ,]', line)
if len(file_inclusion) > 0:
# right now it looks like '=FILENAME,' or '=FILENAME '
for file_included in file_inclusion:
files_included.append(file_included[1:-1])
file_inclusion = re.findall('(?:[ps]*file=|figure=)' +
valid_for_filename + '[,\\]} ]*', line)
if len(file_inclusion) > 0:
# still has the =
for file_included in file_inclusion:
part_before_equals = file_included.split('=')[0]
if len(part_before_equals) != file_included:
file_included = file_included[
len(part_before_equals) + 1:].strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall(
'["\'{\\[]' + valid_for_filename + '[}\\],"\']',
line)
if len(file_inclusion) > 0:
# right now it's got the {} or [] or "" or '' around it still
for file_included in file_inclusion:
file_included = file_included[1:-1]
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall('^' + valid_for_filename + '$', line)
if len(file_inclusion) > 0:
for file_included in file_inclusion:
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall('^' + valid_for_filename + '[,\\} $]', line)
if len(file_inclusion) > 0:
for file_included in file_inclusion:
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall('\\s*' + valid_for_filename + '\\s*$', line)
if len(file_inclusion) > 0:
for file_included in file_inclusion:
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
if files_included != ['ERROR']:
files_included = files_included[1:] # cut off the dummy
for file_included in files_included:
if file_included == '':
files_included.remove(file_included)
if ' ' in file_included:
for subfile in file_included.split(' '):
if subfile not in files_included:
files_included.append(subfile)
if ',' in file_included:
for subfile in file_included.split(' '):
if subfile not in files_included:
files_included.append(subfile)
return files_included | python | def intelligently_find_filenames(line, TeX=False, ext=False,
commas_okay=False):
"""Intelligently find filenames.
Find the filename in the line. We don't support all filenames! Just eps
and ps for now.
:param: line (string): the line we want to get a filename out of
:return: filename ([string, ...]): what is probably the name of the file(s)
"""
files_included = ['ERROR']
if commas_okay:
valid_for_filename = '\\s*[A-Za-z0-9\\-\\=\\+/\\\\_\\.,%#]+'
else:
valid_for_filename = '\\s*[A-Za-z0-9\\-\\=\\+/\\\\_\\.%#]+'
if ext:
valid_for_filename += '\.e*ps[texfi2]*'
if TeX:
valid_for_filename += '[\.latex]*'
file_inclusion = re.findall('=' + valid_for_filename + '[ ,]', line)
if len(file_inclusion) > 0:
# right now it looks like '=FILENAME,' or '=FILENAME '
for file_included in file_inclusion:
files_included.append(file_included[1:-1])
file_inclusion = re.findall('(?:[ps]*file=|figure=)' +
valid_for_filename + '[,\\]} ]*', line)
if len(file_inclusion) > 0:
# still has the =
for file_included in file_inclusion:
part_before_equals = file_included.split('=')[0]
if len(part_before_equals) != file_included:
file_included = file_included[
len(part_before_equals) + 1:].strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall(
'["\'{\\[]' + valid_for_filename + '[}\\],"\']',
line)
if len(file_inclusion) > 0:
# right now it's got the {} or [] or "" or '' around it still
for file_included in file_inclusion:
file_included = file_included[1:-1]
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall('^' + valid_for_filename + '$', line)
if len(file_inclusion) > 0:
for file_included in file_inclusion:
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall('^' + valid_for_filename + '[,\\} $]', line)
if len(file_inclusion) > 0:
for file_included in file_inclusion:
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
file_inclusion = re.findall('\\s*' + valid_for_filename + '\\s*$', line)
if len(file_inclusion) > 0:
for file_included in file_inclusion:
file_included = file_included.strip()
if file_included not in files_included:
files_included.append(file_included)
if files_included != ['ERROR']:
files_included = files_included[1:] # cut off the dummy
for file_included in files_included:
if file_included == '':
files_included.remove(file_included)
if ' ' in file_included:
for subfile in file_included.split(' '):
if subfile not in files_included:
files_included.append(subfile)
if ',' in file_included:
for subfile in file_included.split(' '):
if subfile not in files_included:
files_included.append(subfile)
return files_included | [
"def",
"intelligently_find_filenames",
"(",
"line",
",",
"TeX",
"=",
"False",
",",
"ext",
"=",
"False",
",",
"commas_okay",
"=",
"False",
")",
":",
"files_included",
"=",
"[",
"'ERROR'",
"]",
"if",
"commas_okay",
":",
"valid_for_filename",
"=",
"'\\\\s*[A-Za-z0-9\\\\-\\\\=\\\\+/\\\\\\\\_\\\\.,%#]+'",
"else",
":",
"valid_for_filename",
"=",
"'\\\\s*[A-Za-z0-9\\\\-\\\\=\\\\+/\\\\\\\\_\\\\.%#]+'",
"if",
"ext",
":",
"valid_for_filename",
"+=",
"'\\.e*ps[texfi2]*'",
"if",
"TeX",
":",
"valid_for_filename",
"+=",
"'[\\.latex]*'",
"file_inclusion",
"=",
"re",
".",
"findall",
"(",
"'='",
"+",
"valid_for_filename",
"+",
"'[ ,]'",
",",
"line",
")",
"if",
"len",
"(",
"file_inclusion",
")",
">",
"0",
":",
"# right now it looks like '=FILENAME,' or '=FILENAME '",
"for",
"file_included",
"in",
"file_inclusion",
":",
"files_included",
".",
"append",
"(",
"file_included",
"[",
"1",
":",
"-",
"1",
"]",
")",
"file_inclusion",
"=",
"re",
".",
"findall",
"(",
"'(?:[ps]*file=|figure=)'",
"+",
"valid_for_filename",
"+",
"'[,\\\\]} ]*'",
",",
"line",
")",
"if",
"len",
"(",
"file_inclusion",
")",
">",
"0",
":",
"# still has the =",
"for",
"file_included",
"in",
"file_inclusion",
":",
"part_before_equals",
"=",
"file_included",
".",
"split",
"(",
"'='",
")",
"[",
"0",
"]",
"if",
"len",
"(",
"part_before_equals",
")",
"!=",
"file_included",
":",
"file_included",
"=",
"file_included",
"[",
"len",
"(",
"part_before_equals",
")",
"+",
"1",
":",
"]",
".",
"strip",
"(",
")",
"if",
"file_included",
"not",
"in",
"files_included",
":",
"files_included",
".",
"append",
"(",
"file_included",
")",
"file_inclusion",
"=",
"re",
".",
"findall",
"(",
"'[\"\\'{\\\\[]'",
"+",
"valid_for_filename",
"+",
"'[}\\\\],\"\\']'",
",",
"line",
")",
"if",
"len",
"(",
"file_inclusion",
")",
">",
"0",
":",
"# right now it's got the {} or [] or \"\" or '' around it still",
"for",
"file_included",
"in",
"file_inclusion",
":",
"file_included",
"=",
"file_included",
"[",
"1",
":",
"-",
"1",
"]",
"file_included",
"=",
"file_included",
".",
"strip",
"(",
")",
"if",
"file_included",
"not",
"in",
"files_included",
":",
"files_included",
".",
"append",
"(",
"file_included",
")",
"file_inclusion",
"=",
"re",
".",
"findall",
"(",
"'^'",
"+",
"valid_for_filename",
"+",
"'$'",
",",
"line",
")",
"if",
"len",
"(",
"file_inclusion",
")",
">",
"0",
":",
"for",
"file_included",
"in",
"file_inclusion",
":",
"file_included",
"=",
"file_included",
".",
"strip",
"(",
")",
"if",
"file_included",
"not",
"in",
"files_included",
":",
"files_included",
".",
"append",
"(",
"file_included",
")",
"file_inclusion",
"=",
"re",
".",
"findall",
"(",
"'^'",
"+",
"valid_for_filename",
"+",
"'[,\\\\} $]'",
",",
"line",
")",
"if",
"len",
"(",
"file_inclusion",
")",
">",
"0",
":",
"for",
"file_included",
"in",
"file_inclusion",
":",
"file_included",
"=",
"file_included",
".",
"strip",
"(",
")",
"if",
"file_included",
"not",
"in",
"files_included",
":",
"files_included",
".",
"append",
"(",
"file_included",
")",
"file_inclusion",
"=",
"re",
".",
"findall",
"(",
"'\\\\s*'",
"+",
"valid_for_filename",
"+",
"'\\\\s*$'",
",",
"line",
")",
"if",
"len",
"(",
"file_inclusion",
")",
">",
"0",
":",
"for",
"file_included",
"in",
"file_inclusion",
":",
"file_included",
"=",
"file_included",
".",
"strip",
"(",
")",
"if",
"file_included",
"not",
"in",
"files_included",
":",
"files_included",
".",
"append",
"(",
"file_included",
")",
"if",
"files_included",
"!=",
"[",
"'ERROR'",
"]",
":",
"files_included",
"=",
"files_included",
"[",
"1",
":",
"]",
"# cut off the dummy",
"for",
"file_included",
"in",
"files_included",
":",
"if",
"file_included",
"==",
"''",
":",
"files_included",
".",
"remove",
"(",
"file_included",
")",
"if",
"' '",
"in",
"file_included",
":",
"for",
"subfile",
"in",
"file_included",
".",
"split",
"(",
"' '",
")",
":",
"if",
"subfile",
"not",
"in",
"files_included",
":",
"files_included",
".",
"append",
"(",
"subfile",
")",
"if",
"','",
"in",
"file_included",
":",
"for",
"subfile",
"in",
"file_included",
".",
"split",
"(",
"' '",
")",
":",
"if",
"subfile",
"not",
"in",
"files_included",
":",
"files_included",
".",
"append",
"(",
"subfile",
")",
"return",
"files_included"
] | Intelligently find filenames.
Find the filename in the line. We don't support all filenames! Just eps
and ps for now.
:param: line (string): the line we want to get a filename out of
:return: filename ([string, ...]): what is probably the name of the file(s) | [
"Intelligently",
"find",
"filenames",
"."
] | 12a65350fb9f32d496f9ea57908d9a2771b20474 | https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L774-L869 |
248,675 | inspirehep/plotextractor | plotextractor/extractor.py | get_lines_from_file | def get_lines_from_file(filepath, encoding="UTF-8"):
"""Return an iterator over lines."""
try:
fd = codecs.open(filepath, 'r', encoding)
lines = fd.readlines()
except UnicodeDecodeError:
# Fall back to 'ISO-8859-1'
fd = codecs.open(filepath, 'r', 'ISO-8859-1')
lines = fd.readlines()
finally:
fd.close()
return lines | python | def get_lines_from_file(filepath, encoding="UTF-8"):
"""Return an iterator over lines."""
try:
fd = codecs.open(filepath, 'r', encoding)
lines = fd.readlines()
except UnicodeDecodeError:
# Fall back to 'ISO-8859-1'
fd = codecs.open(filepath, 'r', 'ISO-8859-1')
lines = fd.readlines()
finally:
fd.close()
return lines | [
"def",
"get_lines_from_file",
"(",
"filepath",
",",
"encoding",
"=",
"\"UTF-8\"",
")",
":",
"try",
":",
"fd",
"=",
"codecs",
".",
"open",
"(",
"filepath",
",",
"'r'",
",",
"encoding",
")",
"lines",
"=",
"fd",
".",
"readlines",
"(",
")",
"except",
"UnicodeDecodeError",
":",
"# Fall back to 'ISO-8859-1'",
"fd",
"=",
"codecs",
".",
"open",
"(",
"filepath",
",",
"'r'",
",",
"'ISO-8859-1'",
")",
"lines",
"=",
"fd",
".",
"readlines",
"(",
")",
"finally",
":",
"fd",
".",
"close",
"(",
")",
"return",
"lines"
] | Return an iterator over lines. | [
"Return",
"an",
"iterator",
"over",
"lines",
"."
] | 12a65350fb9f32d496f9ea57908d9a2771b20474 | https://github.com/inspirehep/plotextractor/blob/12a65350fb9f32d496f9ea57908d9a2771b20474/plotextractor/extractor.py#L872-L883 |
248,676 | glenbot/campbx | campbx/campbx.py | CampBX._make_request | def _make_request(self, conf, post_params={}):
"""Make a request to the API and return data in a pythonic object"""
endpoint, requires_auth = conf
# setup the url and the request objects
url = '%s%s.php' % (self.api_url, endpoint)
log.debug('Setting url to %s' % url)
request = urllib2.Request(url)
# tack on authentication if needed
log.debug('Post params: %s' % post_params)
if requires_auth:
post_params.update({
'user': self.username,
'pass': self.password
})
# url encode all parameters
data = urlencode(post_params).encode('utf-8')
# gimme some bitcoins!
try:
log.debug('Requesting data from %s' % url)
response = urllib2.urlopen(request, data)
return json.loads(response.read())
except urllib2.URLError as e:
log.debug('Full error: %s' % e)
if hasattr(e, 'reason'):
self.log.error('Could not reach host. Reason: %s' % e.reason)
elif hasattr(e, 'code'):
self.log.error('Could not fulfill request. Error Code: %s' % e.code)
return None | python | def _make_request(self, conf, post_params={}):
"""Make a request to the API and return data in a pythonic object"""
endpoint, requires_auth = conf
# setup the url and the request objects
url = '%s%s.php' % (self.api_url, endpoint)
log.debug('Setting url to %s' % url)
request = urllib2.Request(url)
# tack on authentication if needed
log.debug('Post params: %s' % post_params)
if requires_auth:
post_params.update({
'user': self.username,
'pass': self.password
})
# url encode all parameters
data = urlencode(post_params).encode('utf-8')
# gimme some bitcoins!
try:
log.debug('Requesting data from %s' % url)
response = urllib2.urlopen(request, data)
return json.loads(response.read())
except urllib2.URLError as e:
log.debug('Full error: %s' % e)
if hasattr(e, 'reason'):
self.log.error('Could not reach host. Reason: %s' % e.reason)
elif hasattr(e, 'code'):
self.log.error('Could not fulfill request. Error Code: %s' % e.code)
return None | [
"def",
"_make_request",
"(",
"self",
",",
"conf",
",",
"post_params",
"=",
"{",
"}",
")",
":",
"endpoint",
",",
"requires_auth",
"=",
"conf",
"# setup the url and the request objects",
"url",
"=",
"'%s%s.php'",
"%",
"(",
"self",
".",
"api_url",
",",
"endpoint",
")",
"log",
".",
"debug",
"(",
"'Setting url to %s'",
"%",
"url",
")",
"request",
"=",
"urllib2",
".",
"Request",
"(",
"url",
")",
"# tack on authentication if needed",
"log",
".",
"debug",
"(",
"'Post params: %s'",
"%",
"post_params",
")",
"if",
"requires_auth",
":",
"post_params",
".",
"update",
"(",
"{",
"'user'",
":",
"self",
".",
"username",
",",
"'pass'",
":",
"self",
".",
"password",
"}",
")",
"# url encode all parameters",
"data",
"=",
"urlencode",
"(",
"post_params",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"# gimme some bitcoins!",
"try",
":",
"log",
".",
"debug",
"(",
"'Requesting data from %s'",
"%",
"url",
")",
"response",
"=",
"urllib2",
".",
"urlopen",
"(",
"request",
",",
"data",
")",
"return",
"json",
".",
"loads",
"(",
"response",
".",
"read",
"(",
")",
")",
"except",
"urllib2",
".",
"URLError",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"'Full error: %s'",
"%",
"e",
")",
"if",
"hasattr",
"(",
"e",
",",
"'reason'",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"'Could not reach host. Reason: %s'",
"%",
"e",
".",
"reason",
")",
"elif",
"hasattr",
"(",
"e",
",",
"'code'",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"'Could not fulfill request. Error Code: %s'",
"%",
"e",
".",
"code",
")",
"return",
"None"
] | Make a request to the API and return data in a pythonic object | [
"Make",
"a",
"request",
"to",
"the",
"API",
"and",
"return",
"data",
"in",
"a",
"pythonic",
"object"
] | b2e34c59ac1d645969e3a56551a1dcd755516094 | https://github.com/glenbot/campbx/blob/b2e34c59ac1d645969e3a56551a1dcd755516094/campbx/campbx.py#L81-L112 |
248,677 | glenbot/campbx | campbx/campbx.py | CampBX._create_endpoints | def _create_endpoints(self):
"""Create all api endpoints using self.endpoint and partial from functools"""
for k, v in self.endpoints.items():
_repr = '%s.%s' % (self.__class__.__name__, k)
self.__dict__[k] = EndPointPartial(self._make_request, v, _repr) | python | def _create_endpoints(self):
"""Create all api endpoints using self.endpoint and partial from functools"""
for k, v in self.endpoints.items():
_repr = '%s.%s' % (self.__class__.__name__, k)
self.__dict__[k] = EndPointPartial(self._make_request, v, _repr) | [
"def",
"_create_endpoints",
"(",
"self",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"endpoints",
".",
"items",
"(",
")",
":",
"_repr",
"=",
"'%s.%s'",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"k",
")",
"self",
".",
"__dict__",
"[",
"k",
"]",
"=",
"EndPointPartial",
"(",
"self",
".",
"_make_request",
",",
"v",
",",
"_repr",
")"
] | Create all api endpoints using self.endpoint and partial from functools | [
"Create",
"all",
"api",
"endpoints",
"using",
"self",
".",
"endpoint",
"and",
"partial",
"from",
"functools"
] | b2e34c59ac1d645969e3a56551a1dcd755516094 | https://github.com/glenbot/campbx/blob/b2e34c59ac1d645969e3a56551a1dcd755516094/campbx/campbx.py#L114-L118 |
248,678 | monkeython/scriba | scriba/content_types/scriba_zip.py | parse | def parse(binary, **params):
"""Turns a ZIP file into a frozen sample."""
binary = io.BytesIO(binary)
collection = list()
with zipfile.ZipFile(binary, 'r') as zip_:
for zip_info in zip_.infolist():
content_type, encoding = mimetypes.guess_type(zip_info.filename)
content = zip_.read(zip_info)
content = content_encodings.get(encoding).decode(content)
content = content_types.get(content_type).parse(content, **params)
collection.apppend((zip_info.filename, content))
return collection | python | def parse(binary, **params):
"""Turns a ZIP file into a frozen sample."""
binary = io.BytesIO(binary)
collection = list()
with zipfile.ZipFile(binary, 'r') as zip_:
for zip_info in zip_.infolist():
content_type, encoding = mimetypes.guess_type(zip_info.filename)
content = zip_.read(zip_info)
content = content_encodings.get(encoding).decode(content)
content = content_types.get(content_type).parse(content, **params)
collection.apppend((zip_info.filename, content))
return collection | [
"def",
"parse",
"(",
"binary",
",",
"*",
"*",
"params",
")",
":",
"binary",
"=",
"io",
".",
"BytesIO",
"(",
"binary",
")",
"collection",
"=",
"list",
"(",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"binary",
",",
"'r'",
")",
"as",
"zip_",
":",
"for",
"zip_info",
"in",
"zip_",
".",
"infolist",
"(",
")",
":",
"content_type",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"zip_info",
".",
"filename",
")",
"content",
"=",
"zip_",
".",
"read",
"(",
"zip_info",
")",
"content",
"=",
"content_encodings",
".",
"get",
"(",
"encoding",
")",
".",
"decode",
"(",
"content",
")",
"content",
"=",
"content_types",
".",
"get",
"(",
"content_type",
")",
".",
"parse",
"(",
"content",
",",
"*",
"*",
"params",
")",
"collection",
".",
"apppend",
"(",
"(",
"zip_info",
".",
"filename",
",",
"content",
")",
")",
"return",
"collection"
] | Turns a ZIP file into a frozen sample. | [
"Turns",
"a",
"ZIP",
"file",
"into",
"a",
"frozen",
"sample",
"."
] | fb8e7636ed07c3d035433fdd153599ac8b24dfc4 | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_zip.py#L13-L24 |
248,679 | monkeython/scriba | scriba/content_types/scriba_zip.py | format | def format(collection, **params):
"""Truns a python object into a ZIP file."""
binary = io.BytesIO()
with zipfile.ZipFile(binary, 'w') as zip_:
now = datetime.datetime.utcnow().timetuple()
for filename, content in collection:
content_type, encoding = mimetypes.guess_type(filename)
content = content_types.get(content_type).parse(content, **params)
content = content_encodings.get(encoding).decode(content)
zip_info = zipfile.ZipInfo(filename, now)
zip_info.file_size = len(content)
zip_.writestr(zip_info, content)
binary.seek(0)
return binary.read() | python | def format(collection, **params):
"""Truns a python object into a ZIP file."""
binary = io.BytesIO()
with zipfile.ZipFile(binary, 'w') as zip_:
now = datetime.datetime.utcnow().timetuple()
for filename, content in collection:
content_type, encoding = mimetypes.guess_type(filename)
content = content_types.get(content_type).parse(content, **params)
content = content_encodings.get(encoding).decode(content)
zip_info = zipfile.ZipInfo(filename, now)
zip_info.file_size = len(content)
zip_.writestr(zip_info, content)
binary.seek(0)
return binary.read() | [
"def",
"format",
"(",
"collection",
",",
"*",
"*",
"params",
")",
":",
"binary",
"=",
"io",
".",
"BytesIO",
"(",
")",
"with",
"zipfile",
".",
"ZipFile",
"(",
"binary",
",",
"'w'",
")",
"as",
"zip_",
":",
"now",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"timetuple",
"(",
")",
"for",
"filename",
",",
"content",
"in",
"collection",
":",
"content_type",
",",
"encoding",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"content",
"=",
"content_types",
".",
"get",
"(",
"content_type",
")",
".",
"parse",
"(",
"content",
",",
"*",
"*",
"params",
")",
"content",
"=",
"content_encodings",
".",
"get",
"(",
"encoding",
")",
".",
"decode",
"(",
"content",
")",
"zip_info",
"=",
"zipfile",
".",
"ZipInfo",
"(",
"filename",
",",
"now",
")",
"zip_info",
".",
"file_size",
"=",
"len",
"(",
"content",
")",
"zip_",
".",
"writestr",
"(",
"zip_info",
",",
"content",
")",
"binary",
".",
"seek",
"(",
"0",
")",
"return",
"binary",
".",
"read",
"(",
")"
] | Truns a python object into a ZIP file. | [
"Truns",
"a",
"python",
"object",
"into",
"a",
"ZIP",
"file",
"."
] | fb8e7636ed07c3d035433fdd153599ac8b24dfc4 | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_zip.py#L27-L40 |
248,680 | minhhoit/yacms | yacms/generic/templatetags/keyword_tags.py | keywords_for | def keywords_for(*args):
"""
Return a list of ``Keyword`` objects for the given model instance
or a model class. In the case of a model class, retrieve all
keywords for all instances of the model and apply a ``weight``
attribute that can be used to create a tag cloud.
"""
# Handle a model instance.
if isinstance(args[0], Model):
obj = args[0]
if getattr(obj, "content_model", None):
obj = obj.get_content_model()
keywords_name = obj.get_keywordsfield_name()
keywords_queryset = getattr(obj, keywords_name).all()
# Keywords may have been prefetched already. If not, we
# need select_related for the actual keywords.
prefetched = getattr(obj, "_prefetched_objects_cache", {})
if keywords_name not in prefetched:
keywords_queryset = keywords_queryset.select_related("keyword")
return [assigned.keyword for assigned in keywords_queryset]
# Handle a model class.
try:
app_label, model = args[0].split(".", 1)
except ValueError:
return []
content_type = ContentType.objects.get(app_label=app_label, model=model)
assigned = AssignedKeyword.objects.filter(content_type=content_type)
keywords = Keyword.objects.filter(assignments__in=assigned)
keywords = keywords.annotate(item_count=Count("assignments"))
if not keywords:
return []
counts = [keyword.item_count for keyword in keywords]
min_count, max_count = min(counts), max(counts)
factor = (settings.TAG_CLOUD_SIZES - 1.)
if min_count != max_count:
factor /= (max_count - min_count)
for kywd in keywords:
kywd.weight = int(round((kywd.item_count - min_count) * factor)) + 1
return keywords | python | def keywords_for(*args):
"""
Return a list of ``Keyword`` objects for the given model instance
or a model class. In the case of a model class, retrieve all
keywords for all instances of the model and apply a ``weight``
attribute that can be used to create a tag cloud.
"""
# Handle a model instance.
if isinstance(args[0], Model):
obj = args[0]
if getattr(obj, "content_model", None):
obj = obj.get_content_model()
keywords_name = obj.get_keywordsfield_name()
keywords_queryset = getattr(obj, keywords_name).all()
# Keywords may have been prefetched already. If not, we
# need select_related for the actual keywords.
prefetched = getattr(obj, "_prefetched_objects_cache", {})
if keywords_name not in prefetched:
keywords_queryset = keywords_queryset.select_related("keyword")
return [assigned.keyword for assigned in keywords_queryset]
# Handle a model class.
try:
app_label, model = args[0].split(".", 1)
except ValueError:
return []
content_type = ContentType.objects.get(app_label=app_label, model=model)
assigned = AssignedKeyword.objects.filter(content_type=content_type)
keywords = Keyword.objects.filter(assignments__in=assigned)
keywords = keywords.annotate(item_count=Count("assignments"))
if not keywords:
return []
counts = [keyword.item_count for keyword in keywords]
min_count, max_count = min(counts), max(counts)
factor = (settings.TAG_CLOUD_SIZES - 1.)
if min_count != max_count:
factor /= (max_count - min_count)
for kywd in keywords:
kywd.weight = int(round((kywd.item_count - min_count) * factor)) + 1
return keywords | [
"def",
"keywords_for",
"(",
"*",
"args",
")",
":",
"# Handle a model instance.",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"Model",
")",
":",
"obj",
"=",
"args",
"[",
"0",
"]",
"if",
"getattr",
"(",
"obj",
",",
"\"content_model\"",
",",
"None",
")",
":",
"obj",
"=",
"obj",
".",
"get_content_model",
"(",
")",
"keywords_name",
"=",
"obj",
".",
"get_keywordsfield_name",
"(",
")",
"keywords_queryset",
"=",
"getattr",
"(",
"obj",
",",
"keywords_name",
")",
".",
"all",
"(",
")",
"# Keywords may have been prefetched already. If not, we",
"# need select_related for the actual keywords.",
"prefetched",
"=",
"getattr",
"(",
"obj",
",",
"\"_prefetched_objects_cache\"",
",",
"{",
"}",
")",
"if",
"keywords_name",
"not",
"in",
"prefetched",
":",
"keywords_queryset",
"=",
"keywords_queryset",
".",
"select_related",
"(",
"\"keyword\"",
")",
"return",
"[",
"assigned",
".",
"keyword",
"for",
"assigned",
"in",
"keywords_queryset",
"]",
"# Handle a model class.",
"try",
":",
"app_label",
",",
"model",
"=",
"args",
"[",
"0",
"]",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"except",
"ValueError",
":",
"return",
"[",
"]",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"app_label",
",",
"model",
"=",
"model",
")",
"assigned",
"=",
"AssignedKeyword",
".",
"objects",
".",
"filter",
"(",
"content_type",
"=",
"content_type",
")",
"keywords",
"=",
"Keyword",
".",
"objects",
".",
"filter",
"(",
"assignments__in",
"=",
"assigned",
")",
"keywords",
"=",
"keywords",
".",
"annotate",
"(",
"item_count",
"=",
"Count",
"(",
"\"assignments\"",
")",
")",
"if",
"not",
"keywords",
":",
"return",
"[",
"]",
"counts",
"=",
"[",
"keyword",
".",
"item_count",
"for",
"keyword",
"in",
"keywords",
"]",
"min_count",
",",
"max_count",
"=",
"min",
"(",
"counts",
")",
",",
"max",
"(",
"counts",
")",
"factor",
"=",
"(",
"settings",
".",
"TAG_CLOUD_SIZES",
"-",
"1.",
")",
"if",
"min_count",
"!=",
"max_count",
":",
"factor",
"/=",
"(",
"max_count",
"-",
"min_count",
")",
"for",
"kywd",
"in",
"keywords",
":",
"kywd",
".",
"weight",
"=",
"int",
"(",
"round",
"(",
"(",
"kywd",
".",
"item_count",
"-",
"min_count",
")",
"*",
"factor",
")",
")",
"+",
"1",
"return",
"keywords"
] | Return a list of ``Keyword`` objects for the given model instance
or a model class. In the case of a model class, retrieve all
keywords for all instances of the model and apply a ``weight``
attribute that can be used to create a tag cloud. | [
"Return",
"a",
"list",
"of",
"Keyword",
"objects",
"for",
"the",
"given",
"model",
"instance",
"or",
"a",
"model",
"class",
".",
"In",
"the",
"case",
"of",
"a",
"model",
"class",
"retrieve",
"all",
"keywords",
"for",
"all",
"instances",
"of",
"the",
"model",
"and",
"apply",
"a",
"weight",
"attribute",
"that",
"can",
"be",
"used",
"to",
"create",
"a",
"tag",
"cloud",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/templatetags/keyword_tags.py#L16-L57 |
248,681 | tBaxter/tango-comments | build/lib/tango_comments/views/moderation.py | flag | def flag(request, comment_id, next=None):
"""
Flags a comment. Confirmation on GET, action on POST.
Templates: :template:`comments/flag.html`,
Context:
comment
the flagged `comments.comment` object
"""
comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)
# Flag on POST
if request.method == 'POST':
perform_flag(request, comment)
return next_redirect(request, fallback=next or 'comments-flag-done',
c=comment.pk)
# Render a form on GET
else:
return render_to_response('comments/flag.html',
{'comment': comment, "next": next},
template.RequestContext(request)
) | python | def flag(request, comment_id, next=None):
"""
Flags a comment. Confirmation on GET, action on POST.
Templates: :template:`comments/flag.html`,
Context:
comment
the flagged `comments.comment` object
"""
comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID)
# Flag on POST
if request.method == 'POST':
perform_flag(request, comment)
return next_redirect(request, fallback=next or 'comments-flag-done',
c=comment.pk)
# Render a form on GET
else:
return render_to_response('comments/flag.html',
{'comment': comment, "next": next},
template.RequestContext(request)
) | [
"def",
"flag",
"(",
"request",
",",
"comment_id",
",",
"next",
"=",
"None",
")",
":",
"comment",
"=",
"get_object_or_404",
"(",
"comments",
".",
"get_model",
"(",
")",
",",
"pk",
"=",
"comment_id",
",",
"site__pk",
"=",
"settings",
".",
"SITE_ID",
")",
"# Flag on POST",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"perform_flag",
"(",
"request",
",",
"comment",
")",
"return",
"next_redirect",
"(",
"request",
",",
"fallback",
"=",
"next",
"or",
"'comments-flag-done'",
",",
"c",
"=",
"comment",
".",
"pk",
")",
"# Render a form on GET",
"else",
":",
"return",
"render_to_response",
"(",
"'comments/flag.html'",
",",
"{",
"'comment'",
":",
"comment",
",",
"\"next\"",
":",
"next",
"}",
",",
"template",
".",
"RequestContext",
"(",
"request",
")",
")"
] | Flags a comment. Confirmation on GET, action on POST.
Templates: :template:`comments/flag.html`,
Context:
comment
the flagged `comments.comment` object | [
"Flags",
"a",
"comment",
".",
"Confirmation",
"on",
"GET",
"action",
"on",
"POST",
"."
] | 1fd335c6fc9e81bba158e42e1483f1a149622ab4 | https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/views/moderation.py#L15-L37 |
248,682 | tBaxter/tango-comments | build/lib/tango_comments/views/moderation.py | perform_flag | def perform_flag(request, comment):
"""
Actually perform the flagging of a comment from a request.
"""
flag, created = comments.models.CommentFlag.objects.get_or_create(
comment = comment,
user = request.user,
flag = comments.models.CommentFlag.SUGGEST_REMOVAL
)
signals.comment_was_flagged.send(
sender = comment.__class__,
comment = comment,
flag = flag,
created = created,
request = request,
) | python | def perform_flag(request, comment):
"""
Actually perform the flagging of a comment from a request.
"""
flag, created = comments.models.CommentFlag.objects.get_or_create(
comment = comment,
user = request.user,
flag = comments.models.CommentFlag.SUGGEST_REMOVAL
)
signals.comment_was_flagged.send(
sender = comment.__class__,
comment = comment,
flag = flag,
created = created,
request = request,
) | [
"def",
"perform_flag",
"(",
"request",
",",
"comment",
")",
":",
"flag",
",",
"created",
"=",
"comments",
".",
"models",
".",
"CommentFlag",
".",
"objects",
".",
"get_or_create",
"(",
"comment",
"=",
"comment",
",",
"user",
"=",
"request",
".",
"user",
",",
"flag",
"=",
"comments",
".",
"models",
".",
"CommentFlag",
".",
"SUGGEST_REMOVAL",
")",
"signals",
".",
"comment_was_flagged",
".",
"send",
"(",
"sender",
"=",
"comment",
".",
"__class__",
",",
"comment",
"=",
"comment",
",",
"flag",
"=",
"flag",
",",
"created",
"=",
"created",
",",
"request",
"=",
"request",
",",
")"
] | Actually perform the flagging of a comment from a request. | [
"Actually",
"perform",
"the",
"flagging",
"of",
"a",
"comment",
"from",
"a",
"request",
"."
] | 1fd335c6fc9e81bba158e42e1483f1a149622ab4 | https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/views/moderation.py#L99-L114 |
248,683 | florianpaquet/mease | mease/server.py | MeaseWebSocketServerProtocol.onConnect | def onConnect(self, request):
"""
Called when a client opens a websocket connection
"""
logger.debug("Connection opened ({peer})".format(peer=self.peer))
self.storage = {}
self._client_id = str(uuid1()) | python | def onConnect(self, request):
"""
Called when a client opens a websocket connection
"""
logger.debug("Connection opened ({peer})".format(peer=self.peer))
self.storage = {}
self._client_id = str(uuid1()) | [
"def",
"onConnect",
"(",
"self",
",",
"request",
")",
":",
"logger",
".",
"debug",
"(",
"\"Connection opened ({peer})\"",
".",
"format",
"(",
"peer",
"=",
"self",
".",
"peer",
")",
")",
"self",
".",
"storage",
"=",
"{",
"}",
"self",
".",
"_client_id",
"=",
"str",
"(",
"uuid1",
"(",
")",
")"
] | Called when a client opens a websocket connection | [
"Called",
"when",
"a",
"client",
"opens",
"a",
"websocket",
"connection"
] | b9fbd08bbe162c8890c2a2124674371170c319ef | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L18-L25 |
248,684 | florianpaquet/mease | mease/server.py | MeaseWebSocketServerProtocol.onOpen | def onOpen(self):
"""
Called when a client has opened a websocket connection
"""
self.factory.add_client(self)
# Publish ON_OPEN message
self.factory.mease.publisher.publish(
message_type=ON_OPEN, client_id=self._client_id, client_storage=self.storage) | python | def onOpen(self):
"""
Called when a client has opened a websocket connection
"""
self.factory.add_client(self)
# Publish ON_OPEN message
self.factory.mease.publisher.publish(
message_type=ON_OPEN, client_id=self._client_id, client_storage=self.storage) | [
"def",
"onOpen",
"(",
"self",
")",
":",
"self",
".",
"factory",
".",
"add_client",
"(",
"self",
")",
"# Publish ON_OPEN message",
"self",
".",
"factory",
".",
"mease",
".",
"publisher",
".",
"publish",
"(",
"message_type",
"=",
"ON_OPEN",
",",
"client_id",
"=",
"self",
".",
"_client_id",
",",
"client_storage",
"=",
"self",
".",
"storage",
")"
] | Called when a client has opened a websocket connection | [
"Called",
"when",
"a",
"client",
"has",
"opened",
"a",
"websocket",
"connection"
] | b9fbd08bbe162c8890c2a2124674371170c319ef | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L27-L35 |
248,685 | florianpaquet/mease | mease/server.py | MeaseWebSocketServerProtocol.onClose | def onClose(self, was_clean, code, reason):
"""
Called when a client closes a websocket connection
"""
logger.debug("Connection closed ({peer})".format(peer=self.peer))
# Publish ON_CLOSE message
self.factory.mease.publisher.publish(
message_type=ON_CLOSE, client_id=self._client_id, client_storage=self.storage)
self.factory.remove_client(self) | python | def onClose(self, was_clean, code, reason):
"""
Called when a client closes a websocket connection
"""
logger.debug("Connection closed ({peer})".format(peer=self.peer))
# Publish ON_CLOSE message
self.factory.mease.publisher.publish(
message_type=ON_CLOSE, client_id=self._client_id, client_storage=self.storage)
self.factory.remove_client(self) | [
"def",
"onClose",
"(",
"self",
",",
"was_clean",
",",
"code",
",",
"reason",
")",
":",
"logger",
".",
"debug",
"(",
"\"Connection closed ({peer})\"",
".",
"format",
"(",
"peer",
"=",
"self",
".",
"peer",
")",
")",
"# Publish ON_CLOSE message",
"self",
".",
"factory",
".",
"mease",
".",
"publisher",
".",
"publish",
"(",
"message_type",
"=",
"ON_CLOSE",
",",
"client_id",
"=",
"self",
".",
"_client_id",
",",
"client_storage",
"=",
"self",
".",
"storage",
")",
"self",
".",
"factory",
".",
"remove_client",
"(",
"self",
")"
] | Called when a client closes a websocket connection | [
"Called",
"when",
"a",
"client",
"closes",
"a",
"websocket",
"connection"
] | b9fbd08bbe162c8890c2a2124674371170c319ef | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L37-L47 |
248,686 | florianpaquet/mease | mease/server.py | MeaseWebSocketServerProtocol.onMessage | def onMessage(self, payload, is_binary):
"""
Called when a client sends a message
"""
if not is_binary:
payload = payload.decode('utf-8')
logger.debug("Incoming message ({peer}) : {message}".format(
peer=self.peer, message=payload))
# Publish ON_RECEIVE message
self.factory.mease.publisher.publish(
message_type=ON_RECEIVE,
client_id=self._client_id,
client_storage=self.storage,
message=payload) | python | def onMessage(self, payload, is_binary):
"""
Called when a client sends a message
"""
if not is_binary:
payload = payload.decode('utf-8')
logger.debug("Incoming message ({peer}) : {message}".format(
peer=self.peer, message=payload))
# Publish ON_RECEIVE message
self.factory.mease.publisher.publish(
message_type=ON_RECEIVE,
client_id=self._client_id,
client_storage=self.storage,
message=payload) | [
"def",
"onMessage",
"(",
"self",
",",
"payload",
",",
"is_binary",
")",
":",
"if",
"not",
"is_binary",
":",
"payload",
"=",
"payload",
".",
"decode",
"(",
"'utf-8'",
")",
"logger",
".",
"debug",
"(",
"\"Incoming message ({peer}) : {message}\"",
".",
"format",
"(",
"peer",
"=",
"self",
".",
"peer",
",",
"message",
"=",
"payload",
")",
")",
"# Publish ON_RECEIVE message",
"self",
".",
"factory",
".",
"mease",
".",
"publisher",
".",
"publish",
"(",
"message_type",
"=",
"ON_RECEIVE",
",",
"client_id",
"=",
"self",
".",
"_client_id",
",",
"client_storage",
"=",
"self",
".",
"storage",
",",
"message",
"=",
"payload",
")"
] | Called when a client sends a message | [
"Called",
"when",
"a",
"client",
"sends",
"a",
"message"
] | b9fbd08bbe162c8890c2a2124674371170c319ef | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L49-L64 |
248,687 | florianpaquet/mease | mease/server.py | MeaseWebSocketServerProtocol.send | def send(self, payload, *args, **kwargs):
"""
Alias for WebSocketServerProtocol `sendMessage` method
"""
if isinstance(payload, (list, dict)):
payload = json.dumps(payload)
self.sendMessage(payload.encode(), *args, **kwargs) | python | def send(self, payload, *args, **kwargs):
"""
Alias for WebSocketServerProtocol `sendMessage` method
"""
if isinstance(payload, (list, dict)):
payload = json.dumps(payload)
self.sendMessage(payload.encode(), *args, **kwargs) | [
"def",
"send",
"(",
"self",
",",
"payload",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"payload",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
"payload",
"=",
"json",
".",
"dumps",
"(",
"payload",
")",
"self",
".",
"sendMessage",
"(",
"payload",
".",
"encode",
"(",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Alias for WebSocketServerProtocol `sendMessage` method | [
"Alias",
"for",
"WebSocketServerProtocol",
"sendMessage",
"method"
] | b9fbd08bbe162c8890c2a2124674371170c319ef | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L75-L82 |
248,688 | florianpaquet/mease | mease/server.py | MeaseWebSocketServerFactory.run_server | def run_server(self):
"""
Runs the WebSocket server
"""
self.protocol = MeaseWebSocketServerProtocol
reactor.listenTCP(port=self.port, factory=self, interface=self.host)
logger.info("Websocket server listening on {address}".format(
address=self.address))
reactor.run() | python | def run_server(self):
"""
Runs the WebSocket server
"""
self.protocol = MeaseWebSocketServerProtocol
reactor.listenTCP(port=self.port, factory=self, interface=self.host)
logger.info("Websocket server listening on {address}".format(
address=self.address))
reactor.run() | [
"def",
"run_server",
"(",
"self",
")",
":",
"self",
".",
"protocol",
"=",
"MeaseWebSocketServerProtocol",
"reactor",
".",
"listenTCP",
"(",
"port",
"=",
"self",
".",
"port",
",",
"factory",
"=",
"self",
",",
"interface",
"=",
"self",
".",
"host",
")",
"logger",
".",
"info",
"(",
"\"Websocket server listening on {address}\"",
".",
"format",
"(",
"address",
"=",
"self",
".",
"address",
")",
")",
"reactor",
".",
"run",
"(",
")"
] | Runs the WebSocket server | [
"Runs",
"the",
"WebSocket",
"server"
] | b9fbd08bbe162c8890c2a2124674371170c319ef | https://github.com/florianpaquet/mease/blob/b9fbd08bbe162c8890c2a2124674371170c319ef/mease/server.py#L129-L140 |
248,689 | blubberdiblub/eztemplate | eztemplate/engines/empy_engine.py | SubsystemWrapper.open | def open(self, name, *args, **kwargs):
"""Open file, possibly relative to a base directory."""
if self.basedir is not None:
name = os.path.join(self.basedir, name)
return em.Subsystem.open(self, name, *args, **kwargs) | python | def open(self, name, *args, **kwargs):
"""Open file, possibly relative to a base directory."""
if self.basedir is not None:
name = os.path.join(self.basedir, name)
return em.Subsystem.open(self, name, *args, **kwargs) | [
"def",
"open",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"basedir",
"is",
"not",
"None",
":",
"name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"basedir",
",",
"name",
")",
"return",
"em",
".",
"Subsystem",
".",
"open",
"(",
"self",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Open file, possibly relative to a base directory. | [
"Open",
"file",
"possibly",
"relative",
"to",
"a",
"base",
"directory",
"."
] | ab5b2b4987c045116d130fd83e216704b8edfb5d | https://github.com/blubberdiblub/eztemplate/blob/ab5b2b4987c045116d130fd83e216704b8edfb5d/eztemplate/engines/empy_engine.py#L32-L37 |
248,690 | Aslan11/wilos-cli | wilos/main.py | get_live_weather | def get_live_weather(lat, lon, writer):
"""Gets the live weather via lat and long"""
requrl = FORECAST_BASE_URL+forecast_api_token+'/'+str(lat)+','+str(lon)
req = requests.get(requrl)
if req.status_code == requests.codes.ok:
weather = req.json()
if not weather['currently']:
click.secho("No live weather currently", fg="red", bold=True)
return
writer.live_weather(weather)
else:
click.secho("There was problem getting live weather", fg="red", bold=True) | python | def get_live_weather(lat, lon, writer):
"""Gets the live weather via lat and long"""
requrl = FORECAST_BASE_URL+forecast_api_token+'/'+str(lat)+','+str(lon)
req = requests.get(requrl)
if req.status_code == requests.codes.ok:
weather = req.json()
if not weather['currently']:
click.secho("No live weather currently", fg="red", bold=True)
return
writer.live_weather(weather)
else:
click.secho("There was problem getting live weather", fg="red", bold=True) | [
"def",
"get_live_weather",
"(",
"lat",
",",
"lon",
",",
"writer",
")",
":",
"requrl",
"=",
"FORECAST_BASE_URL",
"+",
"forecast_api_token",
"+",
"'/'",
"+",
"str",
"(",
"lat",
")",
"+",
"','",
"+",
"str",
"(",
"lon",
")",
"req",
"=",
"requests",
".",
"get",
"(",
"requrl",
")",
"if",
"req",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"ok",
":",
"weather",
"=",
"req",
".",
"json",
"(",
")",
"if",
"not",
"weather",
"[",
"'currently'",
"]",
":",
"click",
".",
"secho",
"(",
"\"No live weather currently\"",
",",
"fg",
"=",
"\"red\"",
",",
"bold",
"=",
"True",
")",
"return",
"writer",
".",
"live_weather",
"(",
"weather",
")",
"else",
":",
"click",
".",
"secho",
"(",
"\"There was problem getting live weather\"",
",",
"fg",
"=",
"\"red\"",
",",
"bold",
"=",
"True",
")"
] | Gets the live weather via lat and long | [
"Gets",
"the",
"live",
"weather",
"via",
"lat",
"and",
"long"
] | 2c3da3589f685e95b4f73237a1bfe56373ea4574 | https://github.com/Aslan11/wilos-cli/blob/2c3da3589f685e95b4f73237a1bfe56373ea4574/wilos/main.py#L53-L64 |
248,691 | markomanninen/abnum | romanize/grc.py | convert | def convert(string, sanitize=False):
"""
Swap characters from script to transliterated version and vice versa.
Optionally sanitize string by using preprocess function.
:param sanitize:
:param string:
:return:
"""
return r.convert(string, (preprocess if sanitize else False)) | python | def convert(string, sanitize=False):
"""
Swap characters from script to transliterated version and vice versa.
Optionally sanitize string by using preprocess function.
:param sanitize:
:param string:
:return:
"""
return r.convert(string, (preprocess if sanitize else False)) | [
"def",
"convert",
"(",
"string",
",",
"sanitize",
"=",
"False",
")",
":",
"return",
"r",
".",
"convert",
"(",
"string",
",",
"(",
"preprocess",
"if",
"sanitize",
"else",
"False",
")",
")"
] | Swap characters from script to transliterated version and vice versa.
Optionally sanitize string by using preprocess function.
:param sanitize:
:param string:
:return: | [
"Swap",
"characters",
"from",
"script",
"to",
"transliterated",
"version",
"and",
"vice",
"versa",
".",
"Optionally",
"sanitize",
"string",
"by",
"using",
"preprocess",
"function",
"."
] | 9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99 | https://github.com/markomanninen/abnum/blob/9bfc8f06f34d9a51aab038638f87e2bb5f9f4c99/romanize/grc.py#L204-L213 |
248,692 | kubernauts/pyk | pyk/util.py | load_yaml | def load_yaml(filename):
"""
Loads a YAML-formatted file.
"""
with open(filename) as f:
ydoc = yaml.safe_load(f.read())
return (ydoc, serialize_tojson(ydoc)) | python | def load_yaml(filename):
"""
Loads a YAML-formatted file.
"""
with open(filename) as f:
ydoc = yaml.safe_load(f.read())
return (ydoc, serialize_tojson(ydoc)) | [
"def",
"load_yaml",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"ydoc",
"=",
"yaml",
".",
"safe_load",
"(",
"f",
".",
"read",
"(",
")",
")",
"return",
"(",
"ydoc",
",",
"serialize_tojson",
"(",
"ydoc",
")",
")"
] | Loads a YAML-formatted file. | [
"Loads",
"a",
"YAML",
"-",
"formatted",
"file",
"."
] | 88531b1f09f23c049b3ad7aa9caebfc02a4a420d | https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/util.py#L12-L18 |
248,693 | kubernauts/pyk | pyk/util.py | serialize_yaml_tofile | def serialize_yaml_tofile(filename, resource):
"""
Serializes a K8S resource to YAML-formatted file.
"""
stream = file(filename, "w")
yaml.dump(resource, stream, default_flow_style=False) | python | def serialize_yaml_tofile(filename, resource):
"""
Serializes a K8S resource to YAML-formatted file.
"""
stream = file(filename, "w")
yaml.dump(resource, stream, default_flow_style=False) | [
"def",
"serialize_yaml_tofile",
"(",
"filename",
",",
"resource",
")",
":",
"stream",
"=",
"file",
"(",
"filename",
",",
"\"w\"",
")",
"yaml",
".",
"dump",
"(",
"resource",
",",
"stream",
",",
"default_flow_style",
"=",
"False",
")"
] | Serializes a K8S resource to YAML-formatted file. | [
"Serializes",
"a",
"K8S",
"resource",
"to",
"YAML",
"-",
"formatted",
"file",
"."
] | 88531b1f09f23c049b3ad7aa9caebfc02a4a420d | https://github.com/kubernauts/pyk/blob/88531b1f09f23c049b3ad7aa9caebfc02a4a420d/pyk/util.py#L20-L25 |
248,694 | monkeython/scriba | scriba/content_types/scriba_json.py | parse | def parse(binary, **params):
"""Turns a JSON structure into a python object."""
encoding = params.get('charset', 'UTF-8')
return json.loads(binary, encoding=encoding) | python | def parse(binary, **params):
"""Turns a JSON structure into a python object."""
encoding = params.get('charset', 'UTF-8')
return json.loads(binary, encoding=encoding) | [
"def",
"parse",
"(",
"binary",
",",
"*",
"*",
"params",
")",
":",
"encoding",
"=",
"params",
".",
"get",
"(",
"'charset'",
",",
"'UTF-8'",
")",
"return",
"json",
".",
"loads",
"(",
"binary",
",",
"encoding",
"=",
"encoding",
")"
] | Turns a JSON structure into a python object. | [
"Turns",
"a",
"JSON",
"structure",
"into",
"a",
"python",
"object",
"."
] | fb8e7636ed07c3d035433fdd153599ac8b24dfc4 | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_json.py#L6-L9 |
248,695 | monkeython/scriba | scriba/content_types/scriba_json.py | format | def format(item, **params):
"""Truns a python object into a JSON structure."""
encoding = params.get('charset', 'UTF-8')
return json.dumps(item, encoding=encoding) | python | def format(item, **params):
"""Truns a python object into a JSON structure."""
encoding = params.get('charset', 'UTF-8')
return json.dumps(item, encoding=encoding) | [
"def",
"format",
"(",
"item",
",",
"*",
"*",
"params",
")",
":",
"encoding",
"=",
"params",
".",
"get",
"(",
"'charset'",
",",
"'UTF-8'",
")",
"return",
"json",
".",
"dumps",
"(",
"item",
",",
"encoding",
"=",
"encoding",
")"
] | Truns a python object into a JSON structure. | [
"Truns",
"a",
"python",
"object",
"into",
"a",
"JSON",
"structure",
"."
] | fb8e7636ed07c3d035433fdd153599ac8b24dfc4 | https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_json.py#L12-L15 |
248,696 | naphatkrit/easyci | easyci/results.py | save_results | def save_results(vcs, signature, result_path, patterns):
"""Save results matching `patterns` at `result_path`.
Args:
vcs (easyci.vcs.base.Vcs) - the VCS object for the actual project
(not the disposable copy)
signature (str) - the project state signature
result_path (str) - the path containing the result, usually
a disposable copy of the project
patterns (str) - `rsync`-compatible patterns matching test results
to save.
"""
results_directory = _get_results_directory(vcs, signature)
if not os.path.exists(results_directory):
os.makedirs(results_directory)
with open(os.path.join(results_directory, 'patterns'), 'w') as f:
f.write('\n'.join(patterns))
if not os.path.exists(os.path.join(results_directory, 'results')):
os.mkdir(os.path.join(results_directory, 'results'))
includes = ['--include={}'.format(x)
for x in patterns]
cmd = ['rsync', '-r'] + includes + ['--exclude=*',
os.path.join(result_path, ''),
os.path.join(results_directory, 'results', '')]
subprocess.check_call(cmd) | python | def save_results(vcs, signature, result_path, patterns):
"""Save results matching `patterns` at `result_path`.
Args:
vcs (easyci.vcs.base.Vcs) - the VCS object for the actual project
(not the disposable copy)
signature (str) - the project state signature
result_path (str) - the path containing the result, usually
a disposable copy of the project
patterns (str) - `rsync`-compatible patterns matching test results
to save.
"""
results_directory = _get_results_directory(vcs, signature)
if not os.path.exists(results_directory):
os.makedirs(results_directory)
with open(os.path.join(results_directory, 'patterns'), 'w') as f:
f.write('\n'.join(patterns))
if not os.path.exists(os.path.join(results_directory, 'results')):
os.mkdir(os.path.join(results_directory, 'results'))
includes = ['--include={}'.format(x)
for x in patterns]
cmd = ['rsync', '-r'] + includes + ['--exclude=*',
os.path.join(result_path, ''),
os.path.join(results_directory, 'results', '')]
subprocess.check_call(cmd) | [
"def",
"save_results",
"(",
"vcs",
",",
"signature",
",",
"result_path",
",",
"patterns",
")",
":",
"results_directory",
"=",
"_get_results_directory",
"(",
"vcs",
",",
"signature",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"results_directory",
")",
":",
"os",
".",
"makedirs",
"(",
"results_directory",
")",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"results_directory",
",",
"'patterns'",
")",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'\\n'",
".",
"join",
"(",
"patterns",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"results_directory",
",",
"'results'",
")",
")",
":",
"os",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"results_directory",
",",
"'results'",
")",
")",
"includes",
"=",
"[",
"'--include={}'",
".",
"format",
"(",
"x",
")",
"for",
"x",
"in",
"patterns",
"]",
"cmd",
"=",
"[",
"'rsync'",
",",
"'-r'",
"]",
"+",
"includes",
"+",
"[",
"'--exclude=*'",
",",
"os",
".",
"path",
".",
"join",
"(",
"result_path",
",",
"''",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"results_directory",
",",
"'results'",
",",
"''",
")",
"]",
"subprocess",
".",
"check_call",
"(",
"cmd",
")"
] | Save results matching `patterns` at `result_path`.
Args:
vcs (easyci.vcs.base.Vcs) - the VCS object for the actual project
(not the disposable copy)
signature (str) - the project state signature
result_path (str) - the path containing the result, usually
a disposable copy of the project
patterns (str) - `rsync`-compatible patterns matching test results
to save. | [
"Save",
"results",
"matching",
"patterns",
"at",
"result_path",
"."
] | 7aee8d7694fe4e2da42ce35b0f700bc840c8b95f | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/results.py#L14-L38 |
248,697 | naphatkrit/easyci | easyci/results.py | sync_results | def sync_results(vcs, signature):
"""Sync the saved results for `signature` back to the project.
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError
"""
results_directory = _get_results_directory(vcs, signature)
if not os.path.exists(results_directory):
raise ResultsNotFoundError
with open(os.path.join(results_directory, 'patterns'), 'r') as f:
patterns = f.read().strip().split()
includes = ['--include={}'.format(x)
for x in patterns]
cmd = ['rsync', '-r'] + includes + ['--exclude=*',
os.path.join(
results_directory, 'results', ''),
os.path.join(vcs.path, '')]
subprocess.check_call(cmd) | python | def sync_results(vcs, signature):
"""Sync the saved results for `signature` back to the project.
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError
"""
results_directory = _get_results_directory(vcs, signature)
if not os.path.exists(results_directory):
raise ResultsNotFoundError
with open(os.path.join(results_directory, 'patterns'), 'r') as f:
patterns = f.read().strip().split()
includes = ['--include={}'.format(x)
for x in patterns]
cmd = ['rsync', '-r'] + includes + ['--exclude=*',
os.path.join(
results_directory, 'results', ''),
os.path.join(vcs.path, '')]
subprocess.check_call(cmd) | [
"def",
"sync_results",
"(",
"vcs",
",",
"signature",
")",
":",
"results_directory",
"=",
"_get_results_directory",
"(",
"vcs",
",",
"signature",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"results_directory",
")",
":",
"raise",
"ResultsNotFoundError",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"results_directory",
",",
"'patterns'",
")",
",",
"'r'",
")",
"as",
"f",
":",
"patterns",
"=",
"f",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"includes",
"=",
"[",
"'--include={}'",
".",
"format",
"(",
"x",
")",
"for",
"x",
"in",
"patterns",
"]",
"cmd",
"=",
"[",
"'rsync'",
",",
"'-r'",
"]",
"+",
"includes",
"+",
"[",
"'--exclude=*'",
",",
"os",
".",
"path",
".",
"join",
"(",
"results_directory",
",",
"'results'",
",",
"''",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"vcs",
".",
"path",
",",
"''",
")",
"]",
"subprocess",
".",
"check_call",
"(",
"cmd",
")"
] | Sync the saved results for `signature` back to the project.
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError | [
"Sync",
"the",
"saved",
"results",
"for",
"signature",
"back",
"to",
"the",
"project",
"."
] | 7aee8d7694fe4e2da42ce35b0f700bc840c8b95f | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/results.py#L41-L61 |
248,698 | naphatkrit/easyci | easyci/results.py | remove_results | def remove_results(vcs, signature):
"""Removed saved results for this signature
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError
"""
results_directory = _get_results_directory(vcs, signature)
if not os.path.exists(results_directory):
raise ResultsNotFoundError
shutil.rmtree(results_directory) | python | def remove_results(vcs, signature):
"""Removed saved results for this signature
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError
"""
results_directory = _get_results_directory(vcs, signature)
if not os.path.exists(results_directory):
raise ResultsNotFoundError
shutil.rmtree(results_directory) | [
"def",
"remove_results",
"(",
"vcs",
",",
"signature",
")",
":",
"results_directory",
"=",
"_get_results_directory",
"(",
"vcs",
",",
"signature",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"results_directory",
")",
":",
"raise",
"ResultsNotFoundError",
"shutil",
".",
"rmtree",
"(",
"results_directory",
")"
] | Removed saved results for this signature
Args:
vcs (easyci.vcs.base.Vcs)
signature (str)
Raises:
ResultsNotFoundError | [
"Removed",
"saved",
"results",
"for",
"this",
"signature"
] | 7aee8d7694fe4e2da42ce35b0f700bc840c8b95f | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/results.py#L64-L76 |
248,699 | naphatkrit/easyci | easyci/results.py | get_signatures_with_results | def get_signatures_with_results(vcs):
"""Returns the list of signatures for which test results are saved.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
List[str]
"""
results_dir = os.path.join(vcs.private_dir(), 'results')
if not os.path.exists(results_dir):
return []
rel_paths = os.listdir(results_dir)
return [p for p in rel_paths if os.path.isdir(os.path.join(results_dir, p))] | python | def get_signatures_with_results(vcs):
"""Returns the list of signatures for which test results are saved.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
List[str]
"""
results_dir = os.path.join(vcs.private_dir(), 'results')
if not os.path.exists(results_dir):
return []
rel_paths = os.listdir(results_dir)
return [p for p in rel_paths if os.path.isdir(os.path.join(results_dir, p))] | [
"def",
"get_signatures_with_results",
"(",
"vcs",
")",
":",
"results_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"vcs",
".",
"private_dir",
"(",
")",
",",
"'results'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"results_dir",
")",
":",
"return",
"[",
"]",
"rel_paths",
"=",
"os",
".",
"listdir",
"(",
"results_dir",
")",
"return",
"[",
"p",
"for",
"p",
"in",
"rel_paths",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"results_dir",
",",
"p",
")",
")",
"]"
] | Returns the list of signatures for which test results are saved.
Args:
vcs (easyci.vcs.base.Vcs)
Returns:
List[str] | [
"Returns",
"the",
"list",
"of",
"signatures",
"for",
"which",
"test",
"results",
"are",
"saved",
"."
] | 7aee8d7694fe4e2da42ce35b0f700bc840c8b95f | https://github.com/naphatkrit/easyci/blob/7aee8d7694fe4e2da42ce35b0f700bc840c8b95f/easyci/results.py#L79-L92 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.