repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
lekhakpadmanabh/Summarizer | smrzr/core.py | _title_similarity_score | def _title_similarity_score(full_text, title):
"""Similarity scores for sentences with
title in descending order"""
sentences = sentence_tokenizer(full_text)
norm = _normalize([title]+sentences)
similarity_matrix = pairwise_kernels(norm, metric='cosine')
return sorted(zip(
... | python | def _title_similarity_score(full_text, title):
"""Similarity scores for sentences with
title in descending order"""
sentences = sentence_tokenizer(full_text)
norm = _normalize([title]+sentences)
similarity_matrix = pairwise_kernels(norm, metric='cosine')
return sorted(zip(
... | [
"def",
"_title_similarity_score",
"(",
"full_text",
",",
"title",
")",
":",
"sentences",
"=",
"sentence_tokenizer",
"(",
"full_text",
")",
"norm",
"=",
"_normalize",
"(",
"[",
"title",
"]",
"+",
"sentences",
")",
"similarity_matrix",
"=",
"pairwise_kernels",
"("... | Similarity scores for sentences with
title in descending order | [
"Similarity",
"scores",
"for",
"sentences",
"with",
"title",
"in",
"descending",
"order"
] | 143456a48217905c720d87331f410e5c8b4e24aa | https://github.com/lekhakpadmanabh/Summarizer/blob/143456a48217905c720d87331f410e5c8b4e24aa/smrzr/core.py#L77-L91 | train |
lekhakpadmanabh/Summarizer | smrzr/core.py | _aggregrate_scores | def _aggregrate_scores(its,tss,num_sentences):
"""rerank the two vectors by
min aggregrate rank, reorder"""
final = []
for i,el in enumerate(its):
for j, le in enumerate(tss):
if el[2] == le[2]:
assert el[1] == le[1]
final.append((el[1],i+j,el[2]))
... | python | def _aggregrate_scores(its,tss,num_sentences):
"""rerank the two vectors by
min aggregrate rank, reorder"""
final = []
for i,el in enumerate(its):
for j, le in enumerate(tss):
if el[2] == le[2]:
assert el[1] == le[1]
final.append((el[1],i+j,el[2]))
... | [
"def",
"_aggregrate_scores",
"(",
"its",
",",
"tss",
",",
"num_sentences",
")",
":",
"final",
"=",
"[",
"]",
"for",
"i",
",",
"el",
"in",
"enumerate",
"(",
"its",
")",
":",
"for",
"j",
",",
"le",
"in",
"enumerate",
"(",
"tss",
")",
":",
"if",
"el... | rerank the two vectors by
min aggregrate rank, reorder | [
"rerank",
"the",
"two",
"vectors",
"by",
"min",
"aggregrate",
"rank",
"reorder"
] | 143456a48217905c720d87331f410e5c8b4e24aa | https://github.com/lekhakpadmanabh/Summarizer/blob/143456a48217905c720d87331f410e5c8b4e24aa/smrzr/core.py#L102-L112 | train |
lekhakpadmanabh/Summarizer | smrzr/core.py | _eval_meta_as_summary | def _eval_meta_as_summary(meta):
"""some crude heuristics for now
most are implemented on bot-side
with domain whitelists"""
if meta == '':
return False
if len(meta)>500:
return False
if 'login' in meta.lower():
return False
return True | python | def _eval_meta_as_summary(meta):
"""some crude heuristics for now
most are implemented on bot-side
with domain whitelists"""
if meta == '':
return False
if len(meta)>500:
return False
if 'login' in meta.lower():
return False
return True | [
"def",
"_eval_meta_as_summary",
"(",
"meta",
")",
":",
"if",
"meta",
"==",
"''",
":",
"return",
"False",
"if",
"len",
"(",
"meta",
")",
">",
"500",
":",
"return",
"False",
"if",
"'login'",
"in",
"meta",
".",
"lower",
"(",
")",
":",
"return",
"False",... | some crude heuristics for now
most are implemented on bot-side
with domain whitelists | [
"some",
"crude",
"heuristics",
"for",
"now",
"most",
"are",
"implemented",
"on",
"bot",
"-",
"side",
"with",
"domain",
"whitelists"
] | 143456a48217905c720d87331f410e5c8b4e24aa | https://github.com/lekhakpadmanabh/Summarizer/blob/143456a48217905c720d87331f410e5c8b4e24aa/smrzr/core.py#L115-L126 | train |
digidotcom/python-wvalib | wva/core.py | WVA.get_subscriptions | def get_subscriptions(self):
"""Return a list of subscriptions currently active for this WVA device
:raises WVAError: if there is a problem getting the subscription list from the WVA
:returns: A list of :class:`WVASubscription` instances
"""
# Example: {'subscriptions': ['subscr... | python | def get_subscriptions(self):
"""Return a list of subscriptions currently active for this WVA device
:raises WVAError: if there is a problem getting the subscription list from the WVA
:returns: A list of :class:`WVASubscription` instances
"""
# Example: {'subscriptions': ['subscr... | [
"def",
"get_subscriptions",
"(",
"self",
")",
":",
"subscriptions",
"=",
"[",
"]",
"for",
"uri",
"in",
"self",
".",
"get_http_client",
"(",
")",
".",
"get",
"(",
"\"subscriptions\"",
")",
".",
"get",
"(",
"'subscriptions'",
")",
":",
"subscriptions",
".",
... | Return a list of subscriptions currently active for this WVA device
:raises WVAError: if there is a problem getting the subscription list from the WVA
:returns: A list of :class:`WVASubscription` instances | [
"Return",
"a",
"list",
"of",
"subscriptions",
"currently",
"active",
"for",
"this",
"WVA",
"device"
] | 4252735e2775f80ebaffd813fbe84046d26906b3 | https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/core.py#L90-L100 | train |
digidotcom/python-wvalib | wva/core.py | WVA.get_event_stream | def get_event_stream(self):
"""Get the event stream associated with this WVA
Note that this event stream is shared across all users of this WVA device
as the WVA only supports a single event stream.
:return: a new :class:`WVAEventStream` instance
"""
if self._event_stre... | python | def get_event_stream(self):
"""Get the event stream associated with this WVA
Note that this event stream is shared across all users of this WVA device
as the WVA only supports a single event stream.
:return: a new :class:`WVAEventStream` instance
"""
if self._event_stre... | [
"def",
"get_event_stream",
"(",
"self",
")",
":",
"if",
"self",
".",
"_event_stream",
"is",
"None",
":",
"self",
".",
"_event_stream",
"=",
"WVAEventStream",
"(",
"self",
".",
"_http_client",
")",
"return",
"self",
".",
"_event_stream"
] | Get the event stream associated with this WVA
Note that this event stream is shared across all users of this WVA device
as the WVA only supports a single event stream.
:return: a new :class:`WVAEventStream` instance | [
"Get",
"the",
"event",
"stream",
"associated",
"with",
"this",
"WVA"
] | 4252735e2775f80ebaffd813fbe84046d26906b3 | https://github.com/digidotcom/python-wvalib/blob/4252735e2775f80ebaffd813fbe84046d26906b3/wva/core.py#L102-L112 | train |
spacetelescope/stsci.imagestats | stsci/imagestats/histogram1d.py | histogram1d._populateHistogram | def _populateHistogram(self):
"""Call the C-code that actually populates the histogram"""
try :
buildHistogram.populate1DHist(self._data, self.histogram,
self.minValue, self.maxValue, self.binWidth)
except:
if ((self._data.max() - self._data.min()) < self.... | python | def _populateHistogram(self):
"""Call the C-code that actually populates the histogram"""
try :
buildHistogram.populate1DHist(self._data, self.histogram,
self.minValue, self.maxValue, self.binWidth)
except:
if ((self._data.max() - self._data.min()) < self.... | [
"def",
"_populateHistogram",
"(",
"self",
")",
":",
"try",
":",
"buildHistogram",
".",
"populate1DHist",
"(",
"self",
".",
"_data",
",",
"self",
".",
"histogram",
",",
"self",
".",
"minValue",
",",
"self",
".",
"maxValue",
",",
"self",
".",
"binWidth",
"... | Call the C-code that actually populates the histogram | [
"Call",
"the",
"C",
"-",
"code",
"that",
"actually",
"populates",
"the",
"histogram"
] | d7fc9fe9783f7ed3dc9e4af47acd357a5ccd68e3 | https://github.com/spacetelescope/stsci.imagestats/blob/d7fc9fe9783f7ed3dc9e4af47acd357a5ccd68e3/stsci/imagestats/histogram1d.py#L55-L68 | train |
spacetelescope/stsci.imagestats | stsci/imagestats/histogram1d.py | histogram1d.getCenters | def getCenters(self):
""" Returns histogram's centers. """
return np.arange(self.histogram.size) * self.binWidth + self.minValue | python | def getCenters(self):
""" Returns histogram's centers. """
return np.arange(self.histogram.size) * self.binWidth + self.minValue | [
"def",
"getCenters",
"(",
"self",
")",
":",
"return",
"np",
".",
"arange",
"(",
"self",
".",
"histogram",
".",
"size",
")",
"*",
"self",
".",
"binWidth",
"+",
"self",
".",
"minValue"
] | Returns histogram's centers. | [
"Returns",
"histogram",
"s",
"centers",
"."
] | d7fc9fe9783f7ed3dc9e4af47acd357a5ccd68e3 | https://github.com/spacetelescope/stsci.imagestats/blob/d7fc9fe9783f7ed3dc9e4af47acd357a5ccd68e3/stsci/imagestats/histogram1d.py#L70-L72 | train |
pennlabs/penn-sdk-python | penn/wharton.py | Wharton.book_reservation | def book_reservation(self, sessionid, roomid, start, end):
""" Book a reservation given the session id, the room id as an integer, and the start and end time as datetimes. """
duration = int((end - start).seconds / 60)
format = "%Y-%m-%dT%H:%M:%S-{}".format(self.get_dst_gmt_timezone())
b... | python | def book_reservation(self, sessionid, roomid, start, end):
""" Book a reservation given the session id, the room id as an integer, and the start and end time as datetimes. """
duration = int((end - start).seconds / 60)
format = "%Y-%m-%dT%H:%M:%S-{}".format(self.get_dst_gmt_timezone())
b... | [
"def",
"book_reservation",
"(",
"self",
",",
"sessionid",
",",
"roomid",
",",
"start",
",",
"end",
")",
":",
"duration",
"=",
"int",
"(",
"(",
"end",
"-",
"start",
")",
".",
"seconds",
"/",
"60",
")",
"format",
"=",
"\"%Y-%m-%dT%H:%M:%S-{}\"",
".",
"fo... | Book a reservation given the session id, the room id as an integer, and the start and end time as datetimes. | [
"Book",
"a",
"reservation",
"given",
"the",
"session",
"id",
"the",
"room",
"id",
"as",
"an",
"integer",
"and",
"the",
"start",
"and",
"end",
"time",
"as",
"datetimes",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/wharton.py#L53-L90 | train |
pennlabs/penn-sdk-python | penn/wharton.py | Wharton.delete_booking | def delete_booking(self, sessionid, booking_id):
""" Deletes a Wharton GSR Booking for a given booking and session id. """
url = "{}{}{}/".format(BASE_URL, "/delete/", booking_id)
cookies = dict(sessionid=sessionid)
try:
resp = requests.get(url, cookies=cookies, headers={'Re... | python | def delete_booking(self, sessionid, booking_id):
""" Deletes a Wharton GSR Booking for a given booking and session id. """
url = "{}{}{}/".format(BASE_URL, "/delete/", booking_id)
cookies = dict(sessionid=sessionid)
try:
resp = requests.get(url, cookies=cookies, headers={'Re... | [
"def",
"delete_booking",
"(",
"self",
",",
"sessionid",
",",
"booking_id",
")",
":",
"url",
"=",
"\"{}{}{}/\"",
".",
"format",
"(",
"BASE_URL",
",",
"\"/delete/\"",
",",
"booking_id",
")",
"cookies",
"=",
"dict",
"(",
"sessionid",
"=",
"sessionid",
")",
"t... | Deletes a Wharton GSR Booking for a given booking and session id. | [
"Deletes",
"a",
"Wharton",
"GSR",
"Booking",
"for",
"a",
"given",
"booking",
"and",
"session",
"id",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/wharton.py#L92-L124 | train |
pennlabs/penn-sdk-python | penn/wharton.py | Wharton.get_wharton_gsrs | def get_wharton_gsrs(self, sessionid, date=None):
""" Make a request to retrieve Wharton GSR listings. """
if date:
date += " {}".format(self.get_dst_gmt_timezone())
else:
date = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%S")
resp = requests.get('https://ap... | python | def get_wharton_gsrs(self, sessionid, date=None):
""" Make a request to retrieve Wharton GSR listings. """
if date:
date += " {}".format(self.get_dst_gmt_timezone())
else:
date = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%S")
resp = requests.get('https://ap... | [
"def",
"get_wharton_gsrs",
"(",
"self",
",",
"sessionid",
",",
"date",
"=",
"None",
")",
":",
"if",
"date",
":",
"date",
"+=",
"\" {}\"",
".",
"format",
"(",
"self",
".",
"get_dst_gmt_timezone",
"(",
")",
")",
"else",
":",
"date",
"=",
"datetime",
".",... | Make a request to retrieve Wharton GSR listings. | [
"Make",
"a",
"request",
"to",
"retrieve",
"Wharton",
"GSR",
"listings",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/wharton.py#L126-L140 | train |
pennlabs/penn-sdk-python | penn/wharton.py | Wharton.switch_format | def switch_format(self, gsr):
""" Convert the Wharton GSR format into the studyspaces API format. """
if "error" in gsr:
return gsr
categories = {
"cid": 1,
"name": "Huntsman Hall",
"rooms": []
}
for time in gsr["times"]:
... | python | def switch_format(self, gsr):
""" Convert the Wharton GSR format into the studyspaces API format. """
if "error" in gsr:
return gsr
categories = {
"cid": 1,
"name": "Huntsman Hall",
"rooms": []
}
for time in gsr["times"]:
... | [
"def",
"switch_format",
"(",
"self",
",",
"gsr",
")",
":",
"if",
"\"error\"",
"in",
"gsr",
":",
"return",
"gsr",
"categories",
"=",
"{",
"\"cid\"",
":",
"1",
",",
"\"name\"",
":",
"\"Huntsman Hall\"",
",",
"\"rooms\"",
":",
"[",
"]",
"}",
"for",
"time"... | Convert the Wharton GSR format into the studyspaces API format. | [
"Convert",
"the",
"Wharton",
"GSR",
"format",
"into",
"the",
"studyspaces",
"API",
"format",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/wharton.py#L142-L184 | train |
pennlabs/penn-sdk-python | penn/wharton.py | Wharton.get_wharton_gsrs_formatted | def get_wharton_gsrs_formatted(self, sessionid, date=None):
""" Return the wharton GSR listing formatted in studyspaces format. """
gsrs = self.get_wharton_gsrs(sessionid, date)
return self.switch_format(gsrs) | python | def get_wharton_gsrs_formatted(self, sessionid, date=None):
""" Return the wharton GSR listing formatted in studyspaces format. """
gsrs = self.get_wharton_gsrs(sessionid, date)
return self.switch_format(gsrs) | [
"def",
"get_wharton_gsrs_formatted",
"(",
"self",
",",
"sessionid",
",",
"date",
"=",
"None",
")",
":",
"gsrs",
"=",
"self",
".",
"get_wharton_gsrs",
"(",
"sessionid",
",",
"date",
")",
"return",
"self",
".",
"switch_format",
"(",
"gsrs",
")"
] | Return the wharton GSR listing formatted in studyspaces format. | [
"Return",
"the",
"wharton",
"GSR",
"listing",
"formatted",
"in",
"studyspaces",
"format",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/wharton.py#L186-L189 | train |
cloudbase/python-hnvclient | hnv/config/options.py | get_options | def get_options():
"""Collect all the options info from the other modules."""
options = collections.defaultdict(list)
for opt_class in config_factory.get_options():
if not issubclass(opt_class, config_base.Options):
continue
config_options = opt_class(None)
options[config... | python | def get_options():
"""Collect all the options info from the other modules."""
options = collections.defaultdict(list)
for opt_class in config_factory.get_options():
if not issubclass(opt_class, config_base.Options):
continue
config_options = opt_class(None)
options[config... | [
"def",
"get_options",
"(",
")",
":",
"options",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"opt_class",
"in",
"config_factory",
".",
"get_options",
"(",
")",
":",
"if",
"not",
"issubclass",
"(",
"opt_class",
",",
"config_base",
".",
"... | Collect all the options info from the other modules. | [
"Collect",
"all",
"the",
"options",
"info",
"from",
"the",
"other",
"modules",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/config/options.py#L26-L34 | train |
pennlabs/penn-sdk-python | penn/laundry.py | Laundry.check_is_working | def check_is_working(self):
""" Returns True if the wash alert web interface seems to be
working properly, or False otherwise.
>>> l.check_is_working()
"""
try:
r = requests.post("http://{}/".format(LAUNDRY_DOMAIN), timeout=60, data={
"locationid": "5... | python | def check_is_working(self):
""" Returns True if the wash alert web interface seems to be
working properly, or False otherwise.
>>> l.check_is_working()
"""
try:
r = requests.post("http://{}/".format(LAUNDRY_DOMAIN), timeout=60, data={
"locationid": "5... | [
"def",
"check_is_working",
"(",
"self",
")",
":",
"try",
":",
"r",
"=",
"requests",
".",
"post",
"(",
"\"http://{}/\"",
".",
"format",
"(",
"LAUNDRY_DOMAIN",
")",
",",
"timeout",
"=",
"60",
",",
"data",
"=",
"{",
"\"locationid\"",
":",
"\"5faec7e9-a4aa-47c... | Returns True if the wash alert web interface seems to be
working properly, or False otherwise.
>>> l.check_is_working() | [
"Returns",
"True",
"if",
"the",
"wash",
"alert",
"web",
"interface",
"seems",
"to",
"be",
"working",
"properly",
"or",
"False",
"otherwise",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/laundry.py#L153-L170 | train |
pennlabs/penn-sdk-python | penn/laundry.py | Laundry.machine_usage | def machine_usage(self, hall_no):
"""Returns the average usage of laundry machines every hour
for a given hall.
The usages are returned in a dictionary, with the key being
the day of the week, and the value being an array listing the usages
per hour.
:param hall_no:
... | python | def machine_usage(self, hall_no):
"""Returns the average usage of laundry machines every hour
for a given hall.
The usages are returned in a dictionary, with the key being
the day of the week, and the value being an array listing the usages
per hour.
:param hall_no:
... | [
"def",
"machine_usage",
"(",
"self",
",",
"hall_no",
")",
":",
"try",
":",
"num",
"=",
"int",
"(",
"hall_no",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"Room Number must be integer\"",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"USAG... | Returns the average usage of laundry machines every hour
for a given hall.
The usages are returned in a dictionary, with the key being
the day of the week, and the value being an array listing the usages
per hour.
:param hall_no:
integer corresponding to the id num... | [
"Returns",
"the",
"average",
"usage",
"of",
"laundry",
"machines",
"every",
"hour",
"for",
"a",
"given",
"hall",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/laundry.py#L172-L202 | train |
lambdalisue/notify | src/notify/mailer.py | create_message | def create_message(from_addr, to_addr, subject, body, encoding=None):
"""
Create message object for sending email
Parameters
----------
from_addr : string
An email address used for 'From' attribute
to_addr : string
An email address used for 'To' attribute
subject : string
... | python | def create_message(from_addr, to_addr, subject, body, encoding=None):
"""
Create message object for sending email
Parameters
----------
from_addr : string
An email address used for 'From' attribute
to_addr : string
An email address used for 'To' attribute
subject : string
... | [
"def",
"create_message",
"(",
"from_addr",
",",
"to_addr",
",",
"subject",
",",
"body",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"encoding",
"==",
"\"None\"",
":",
"encoding",
"=",
"None",
"if",
"not",
"encoding",
":",
"encoding",
"=",
"'utf-8'",
"m... | Create message object for sending email
Parameters
----------
from_addr : string
An email address used for 'From' attribute
to_addr : string
An email address used for 'To' attribute
subject : string
An email subject string
body : string
An email body string
e... | [
"Create",
"message",
"object",
"for",
"sending",
"email"
] | 1b6d7d1faa2cea13bfaa1f35130f279a0115e686 | https://github.com/lambdalisue/notify/blob/1b6d7d1faa2cea13bfaa1f35130f279a0115e686/src/notify/mailer.py#L11-L42 | train |
pennlabs/penn-sdk-python | penn/studyspaces.py | StudySpaces._obtain_token | def _obtain_token(self):
"""Obtain an auth token from client id and client secret."""
# don't renew token if hasn't expired yet
if self.expiration and self.expiration > datetime.datetime.now():
return
resp = requests.post("{}/1.1/oauth/token".format(API_URL), data={
... | python | def _obtain_token(self):
"""Obtain an auth token from client id and client secret."""
# don't renew token if hasn't expired yet
if self.expiration and self.expiration > datetime.datetime.now():
return
resp = requests.post("{}/1.1/oauth/token".format(API_URL), data={
... | [
"def",
"_obtain_token",
"(",
"self",
")",
":",
"if",
"self",
".",
"expiration",
"and",
"self",
".",
"expiration",
">",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
":",
"return",
"resp",
"=",
"requests",
".",
"post",
"(",
"\"{}/1.1/oauth/token\"",
... | Obtain an auth token from client id and client secret. | [
"Obtain",
"an",
"auth",
"token",
"from",
"client",
"id",
"and",
"client",
"secret",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L30-L48 | train |
pennlabs/penn-sdk-python | penn/studyspaces.py | StudySpaces._request | def _request(self, *args, **kwargs):
"""Make a signed request to the libcal API."""
if not self.token:
self._obtain_token()
headers = {
"Authorization": "Bearer {}".format(self.token)
}
# add authorization headers
if "headers" in kwargs:
... | python | def _request(self, *args, **kwargs):
"""Make a signed request to the libcal API."""
if not self.token:
self._obtain_token()
headers = {
"Authorization": "Bearer {}".format(self.token)
}
# add authorization headers
if "headers" in kwargs:
... | [
"def",
"_request",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"token",
":",
"self",
".",
"_obtain_token",
"(",
")",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"\"Bearer {}\"",
".",
"format",
"(",
"self",... | Make a signed request to the libcal API. | [
"Make",
"a",
"signed",
"request",
"to",
"the",
"libcal",
"API",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L50-L78 | train |
pennlabs/penn-sdk-python | penn/studyspaces.py | StudySpaces.get_rooms | def get_rooms(self, lid, start=None, end=None):
"""Returns a list of rooms and their availabilities, grouped by category.
:param lid: The ID of the location to retrieve rooms for.
:type lid: int
:param start: The start range for the availabilities to retrieve, in YYYY-MM-DD format.
... | python | def get_rooms(self, lid, start=None, end=None):
"""Returns a list of rooms and their availabilities, grouped by category.
:param lid: The ID of the location to retrieve rooms for.
:type lid: int
:param start: The start range for the availabilities to retrieve, in YYYY-MM-DD format.
... | [
"def",
"get_rooms",
"(",
"self",
",",
"lid",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"range_str",
"=",
"\"availability\"",
"if",
"start",
":",
"start_datetime",
"=",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"datetime",
".",... | Returns a list of rooms and their availabilities, grouped by category.
:param lid: The ID of the location to retrieve rooms for.
:type lid: int
:param start: The start range for the availabilities to retrieve, in YYYY-MM-DD format.
:type start: str
:param end: The end range for ... | [
"Returns",
"a",
"list",
"of",
"rooms",
"and",
"their",
"availabilities",
"grouped",
"by",
"category",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L93-L167 | train |
pennlabs/penn-sdk-python | penn/studyspaces.py | StudySpaces.book_room | def book_room(self, item, start, end, fname, lname, email, nickname, custom={}, test=False):
"""Books a room given the required information.
:param item:
The ID of the room to book.
:type item: int
:param start:
The start time range of when to book the room, in t... | python | def book_room(self, item, start, end, fname, lname, email, nickname, custom={}, test=False):
"""Books a room given the required information.
:param item:
The ID of the room to book.
:type item: int
:param start:
The start time range of when to book the room, in t... | [
"def",
"book_room",
"(",
"self",
",",
"item",
",",
"start",
",",
"end",
",",
"fname",
",",
"lname",
",",
"email",
",",
"nickname",
",",
"custom",
"=",
"{",
"}",
",",
"test",
"=",
"False",
")",
":",
"data",
"=",
"{",
"\"start\"",
":",
"start",
","... | Books a room given the required information.
:param item:
The ID of the room to book.
:type item: int
:param start:
The start time range of when to book the room, in the format returned by the LibCal API.
:type start: str
:param end:
The end t... | [
"Books",
"a",
"room",
"given",
"the",
"required",
"information",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L169-L231 | train |
pennlabs/penn-sdk-python | penn/studyspaces.py | StudySpaces.cancel_room | def cancel_room(self, booking_id):
"""Cancel a room given a booking id.
:param booking_id: A booking id or a list of booking ids (separated by commas) to cancel.
:type booking_id: str
"""
resp = self._request("POST", "/1.1/space/cancel/{}".format(booking_id))
return resp... | python | def cancel_room(self, booking_id):
"""Cancel a room given a booking id.
:param booking_id: A booking id or a list of booking ids (separated by commas) to cancel.
:type booking_id: str
"""
resp = self._request("POST", "/1.1/space/cancel/{}".format(booking_id))
return resp... | [
"def",
"cancel_room",
"(",
"self",
",",
"booking_id",
")",
":",
"resp",
"=",
"self",
".",
"_request",
"(",
"\"POST\"",
",",
"\"/1.1/space/cancel/{}\"",
".",
"format",
"(",
"booking_id",
")",
")",
"return",
"resp",
".",
"json",
"(",
")"
] | Cancel a room given a booking id.
:param booking_id: A booking id or a list of booking ids (separated by commas) to cancel.
:type booking_id: str | [
"Cancel",
"a",
"room",
"given",
"a",
"booking",
"id",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L233-L240 | train |
pennlabs/penn-sdk-python | penn/studyspaces.py | StudySpaces.get_reservations | def get_reservations(self, email, date, timeout=None):
"""Gets reservations for a given email.
:param email: the email of the user who's reservations are to be fetched
:type email: str
"""
try:
resp = self._request("GET", "/1.1/space/bookings?email={}&date={}&limit=1... | python | def get_reservations(self, email, date, timeout=None):
"""Gets reservations for a given email.
:param email: the email of the user who's reservations are to be fetched
:type email: str
"""
try:
resp = self._request("GET", "/1.1/space/bookings?email={}&date={}&limit=1... | [
"def",
"get_reservations",
"(",
"self",
",",
"email",
",",
"date",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"_request",
"(",
"\"GET\"",
",",
"\"/1.1/space/bookings?email={}&date={}&limit=100\"",
".",
"format",
"(",
"email",
... | Gets reservations for a given email.
:param email: the email of the user who's reservations are to be fetched
:type email: str | [
"Gets",
"reservations",
"for",
"a",
"given",
"email",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L242-L254 | train |
pennlabs/penn-sdk-python | penn/studyspaces.py | StudySpaces.get_reservations_for_booking_ids | def get_reservations_for_booking_ids(self, booking_ids):
"""Gets booking information for a given list of booking ids.
:param booking_ids: a booking id or a list of room ids (comma separated).
:type booking_ids: string
"""
try:
resp = self._request("GET", "/1.1/space/... | python | def get_reservations_for_booking_ids(self, booking_ids):
"""Gets booking information for a given list of booking ids.
:param booking_ids: a booking id or a list of room ids (comma separated).
:type booking_ids: string
"""
try:
resp = self._request("GET", "/1.1/space/... | [
"def",
"get_reservations_for_booking_ids",
"(",
"self",
",",
"booking_ids",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"_request",
"(",
"\"GET\"",
",",
"\"/1.1/space/booking/{}\"",
".",
"format",
"(",
"booking_ids",
")",
")",
"except",
"resp",
".",
"excep... | Gets booking information for a given list of booking ids.
:param booking_ids: a booking id or a list of room ids (comma separated).
:type booking_ids: string | [
"Gets",
"booking",
"information",
"for",
"a",
"given",
"list",
"of",
"booking",
"ids",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L256-L266 | train |
pennlabs/penn-sdk-python | penn/studyspaces.py | StudySpaces.get_room_info | def get_room_info(self, room_ids):
"""Gets room information for a given list of ids.
:param room_ids: a room id or a list of room ids (comma separated).
:type room_ids: string
"""
try:
resp = self._request("GET", "/1.1/space/item/{}".format(room_ids))
roo... | python | def get_room_info(self, room_ids):
"""Gets room information for a given list of ids.
:param room_ids: a room id or a list of room ids (comma separated).
:type room_ids: string
"""
try:
resp = self._request("GET", "/1.1/space/item/{}".format(room_ids))
roo... | [
"def",
"get_room_info",
"(",
"self",
",",
"room_ids",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"_request",
"(",
"\"GET\"",
",",
"\"/1.1/space/item/{}\"",
".",
"format",
"(",
"room_ids",
")",
")",
"rooms",
"=",
"resp",
".",
"json",
"(",
")",
"for... | Gets room information for a given list of ids.
:param room_ids: a room id or a list of room ids (comma separated).
:type room_ids: string | [
"Gets",
"room",
"information",
"for",
"a",
"given",
"list",
"of",
"ids",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/studyspaces.py#L268-L286 | train |
evolbioinfo/pastml | pastml/acr.py | reconstruct_ancestral_states | def reconstruct_ancestral_states(tree, character, states, prediction_method=MPPA, model=F81,
params=None, avg_br_len=None, num_nodes=None, num_tips=None,
force_joint=True):
"""
Reconstructs ancestral states for the given character on the given tr... | python | def reconstruct_ancestral_states(tree, character, states, prediction_method=MPPA, model=F81,
params=None, avg_br_len=None, num_nodes=None, num_tips=None,
force_joint=True):
"""
Reconstructs ancestral states for the given character on the given tr... | [
"def",
"reconstruct_ancestral_states",
"(",
"tree",
",",
"character",
",",
"states",
",",
"prediction_method",
"=",
"MPPA",
",",
"model",
"=",
"F81",
",",
"params",
"=",
"None",
",",
"avg_br_len",
"=",
"None",
",",
"num_nodes",
"=",
"None",
",",
"num_tips",
... | Reconstructs ancestral states for the given character on the given tree.
:param character: character whose ancestral states are to be reconstructed.
:type character: str
:param tree: tree whose ancestral state are to be reconstructed,
annotated with the feature specified as `character` containing n... | [
"Reconstructs",
"ancestral",
"states",
"for",
"the",
"given",
"character",
"on",
"the",
"given",
"tree",
"."
] | df8a375841525738383e59548eed3441b07dbd3e | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/acr.py#L137-L197 | train |
evolbioinfo/pastml | pastml/acr.py | acr | def acr(tree, df, prediction_method=MPPA, model=F81, column2parameters=None, force_joint=True):
"""
Reconstructs ancestral states for the given tree and
all the characters specified as columns of the given annotation dataframe.
:param df: dataframe indexed with tree node names
and containing ch... | python | def acr(tree, df, prediction_method=MPPA, model=F81, column2parameters=None, force_joint=True):
"""
Reconstructs ancestral states for the given tree and
all the characters specified as columns of the given annotation dataframe.
:param df: dataframe indexed with tree node names
and containing ch... | [
"def",
"acr",
"(",
"tree",
",",
"df",
",",
"prediction_method",
"=",
"MPPA",
",",
"model",
"=",
"F81",
",",
"column2parameters",
"=",
"None",
",",
"force_joint",
"=",
"True",
")",
":",
"for",
"c",
"in",
"df",
".",
"columns",
":",
"df",
"[",
"c",
"]... | Reconstructs ancestral states for the given tree and
all the characters specified as columns of the given annotation dataframe.
:param df: dataframe indexed with tree node names
and containing characters for which ACR should be performed as columns.
:type df: pandas.DataFrame
:param tree: tree ... | [
"Reconstructs",
"ancestral",
"states",
"for",
"the",
"given",
"tree",
"and",
"all",
"the",
"characters",
"specified",
"as",
"columns",
"of",
"the",
"given",
"annotation",
"dataframe",
"."
] | df8a375841525738383e59548eed3441b07dbd3e | https://github.com/evolbioinfo/pastml/blob/df8a375841525738383e59548eed3441b07dbd3e/pastml/acr.py#L200-L276 | train |
geophysics-ubonn/reda | lib/reda/utils/eit_fzj_utils.py | compute_correction_factors | def compute_correction_factors(data, true_conductivity, elem_file, elec_file):
"""Compute correction factors for 2D rhizotron geometries, following
Weigand and Kemna, 2017, Biogeosciences
https://doi.org/10.5194/bg-14-921-2017
Parameters
----------
data : :py:class:`pandas.DataFrame`
m... | python | def compute_correction_factors(data, true_conductivity, elem_file, elec_file):
"""Compute correction factors for 2D rhizotron geometries, following
Weigand and Kemna, 2017, Biogeosciences
https://doi.org/10.5194/bg-14-921-2017
Parameters
----------
data : :py:class:`pandas.DataFrame`
m... | [
"def",
"compute_correction_factors",
"(",
"data",
",",
"true_conductivity",
",",
"elem_file",
",",
"elec_file",
")",
":",
"settings",
"=",
"{",
"'rho'",
":",
"100",
",",
"'pha'",
":",
"0",
",",
"'elem'",
":",
"'elem.dat'",
",",
"'elec'",
":",
"'elec.dat'",
... | Compute correction factors for 2D rhizotron geometries, following
Weigand and Kemna, 2017, Biogeosciences
https://doi.org/10.5194/bg-14-921-2017
Parameters
----------
data : :py:class:`pandas.DataFrame`
measured data
true_conductivity : float
Conductivity in S/m
elem_file :... | [
"Compute",
"correction",
"factors",
"for",
"2D",
"rhizotron",
"geometries",
"following",
"Weigand",
"and",
"Kemna",
"2017",
"Biogeosciences"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/eit_fzj_utils.py#L12-L62 | train |
shexSpec/grammar | parsers/python/pyshexc/parser_impl/generate_shexj.py | rdf_suffix | def rdf_suffix(fmt: str) -> str:
""" Map the RDF format to the approproate suffix """
for k, v in SUFFIX_FORMAT_MAP.items():
if fmt == v:
return k
return 'rdf' | python | def rdf_suffix(fmt: str) -> str:
""" Map the RDF format to the approproate suffix """
for k, v in SUFFIX_FORMAT_MAP.items():
if fmt == v:
return k
return 'rdf' | [
"def",
"rdf_suffix",
"(",
"fmt",
":",
"str",
")",
"->",
"str",
":",
"for",
"k",
",",
"v",
"in",
"SUFFIX_FORMAT_MAP",
".",
"items",
"(",
")",
":",
"if",
"fmt",
"==",
"v",
":",
"return",
"k",
"return",
"'rdf'"
] | Map the RDF format to the approproate suffix | [
"Map",
"the",
"RDF",
"format",
"to",
"the",
"approproate",
"suffix"
] | 4497cd1f73fa6703bca6e2cb53ba9c120f22e48c | https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/generate_shexj.py#L143-L148 | train |
geophysics-ubonn/reda | lib/reda/exporters/bert.py | export_bert | def export_bert(data, electrodes, filename):
"""Export to unified data format used in pyGIMLi & BERT.
Parameters
----------
data : :py:class:`pandas.DataFrame`
DataFrame with at least a, b, m, n and r.
electrodes : :py:class:`pandas.DataFrame`
DataFrame with electrode positions.
... | python | def export_bert(data, electrodes, filename):
"""Export to unified data format used in pyGIMLi & BERT.
Parameters
----------
data : :py:class:`pandas.DataFrame`
DataFrame with at least a, b, m, n and r.
electrodes : :py:class:`pandas.DataFrame`
DataFrame with electrode positions.
... | [
"def",
"export_bert",
"(",
"data",
",",
"electrodes",
",",
"filename",
")",
":",
"if",
"has_multiple_timesteps",
"(",
"data",
")",
":",
"for",
"i",
",",
"timestep",
"in",
"enumerate",
"(",
"split_timesteps",
"(",
"data",
")",
")",
":",
"export_bert",
"(",
... | Export to unified data format used in pyGIMLi & BERT.
Parameters
----------
data : :py:class:`pandas.DataFrame`
DataFrame with at least a, b, m, n and r.
electrodes : :py:class:`pandas.DataFrame`
DataFrame with electrode positions.
filename : str
String of the output filenam... | [
"Export",
"to",
"unified",
"data",
"format",
"used",
"in",
"pyGIMLi",
"&",
"BERT",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/exporters/bert.py#L4-L73 | train |
cfobel/webcam-recorder | webcam_recorder/view.py | VideoSelectorView.reset | def reset(self, index=None):
'''
Reset the points for the specified index position. If no index is
specified, reset points for all point handlers.
'''
points_handler_count = len(self.registration_view.points)
if index is None:
indexes = range(points_handler_c... | python | def reset(self, index=None):
'''
Reset the points for the specified index position. If no index is
specified, reset points for all point handlers.
'''
points_handler_count = len(self.registration_view.points)
if index is None:
indexes = range(points_handler_c... | [
"def",
"reset",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"points_handler_count",
"=",
"len",
"(",
"self",
".",
"registration_view",
".",
"points",
")",
"if",
"index",
"is",
"None",
":",
"indexes",
"=",
"range",
"(",
"points_handler_count",
")",
... | Reset the points for the specified index position. If no index is
specified, reset points for all point handlers. | [
"Reset",
"the",
"points",
"for",
"the",
"specified",
"index",
"position",
".",
"If",
"no",
"index",
"is",
"specified",
"reset",
"points",
"for",
"all",
"point",
"handlers",
"."
] | ffeb57c9044033fbea6372b3e642b83fd42dea87 | https://github.com/cfobel/webcam-recorder/blob/ffeb57c9044033fbea6372b3e642b83fd42dea87/webcam_recorder/view.py#L102-L118 | train |
geophysics-ubonn/reda | lib/reda/importers/res2dinv.py | _read_file | def _read_file(filename):
"""
Read a res2dinv-file and return the header
Parameters
----------
filename : string
Data filename
Returns
------
type : int
type of array extracted from header
file_data : :py:class:`StringIO.StringIO`
content of file in a String... | python | def _read_file(filename):
"""
Read a res2dinv-file and return the header
Parameters
----------
filename : string
Data filename
Returns
------
type : int
type of array extracted from header
file_data : :py:class:`StringIO.StringIO`
content of file in a String... | [
"def",
"_read_file",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fid2",
":",
"abem_data_orig",
"=",
"fid2",
".",
"read",
"(",
")",
"fid",
"=",
"StringIO",
"(",
")",
"fid",
".",
"write",
"(",
"abem_data_orig",
"... | Read a res2dinv-file and return the header
Parameters
----------
filename : string
Data filename
Returns
------
type : int
type of array extracted from header
file_data : :py:class:`StringIO.StringIO`
content of file in a StringIO object | [
"Read",
"a",
"res2dinv",
"-",
"file",
"and",
"return",
"the",
"header"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/res2dinv.py#L15-L46 | train |
geophysics-ubonn/reda | lib/reda/importers/res2dinv.py | add_dat_file | def add_dat_file(filename, settings, container=None, **kwargs):
""" Read a RES2DINV-style file produced by the ABEM export program.
"""
# each type is read by a different function
importers = {
# general array type
11: _read_general_type,
}
file_type, content = _read_file(filena... | python | def add_dat_file(filename, settings, container=None, **kwargs):
""" Read a RES2DINV-style file produced by the ABEM export program.
"""
# each type is read by a different function
importers = {
# general array type
11: _read_general_type,
}
file_type, content = _read_file(filena... | [
"def",
"add_dat_file",
"(",
"filename",
",",
"settings",
",",
"container",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"importers",
"=",
"{",
"11",
":",
"_read_general_type",
",",
"}",
"file_type",
",",
"content",
"=",
"_read_file",
"(",
"filename",
")",
... | Read a RES2DINV-style file produced by the ABEM export program. | [
"Read",
"a",
"RES2DINV",
"-",
"style",
"file",
"produced",
"by",
"the",
"ABEM",
"export",
"program",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/res2dinv.py#L142-L170 | train |
lambdalisue/notify | src/notify/wizard.py | console_input | def console_input(default, validation=None, allow_empty=False):
"""
Get user input value from stdin
Parameters
----------
default : string
A default value. It will be used when user input nothing.
validation : callable
A validation function. The validation function must raise an... | python | def console_input(default, validation=None, allow_empty=False):
"""
Get user input value from stdin
Parameters
----------
default : string
A default value. It will be used when user input nothing.
validation : callable
A validation function. The validation function must raise an... | [
"def",
"console_input",
"(",
"default",
",",
"validation",
"=",
"None",
",",
"allow_empty",
"=",
"False",
")",
":",
"value",
"=",
"raw_input",
"(",
"\"> \"",
")",
"or",
"default",
"if",
"value",
"==",
"\"\"",
"and",
"not",
"allow_empty",
":",
"print",
"\... | Get user input value from stdin
Parameters
----------
default : string
A default value. It will be used when user input nothing.
validation : callable
A validation function. The validation function must raise an error
when validation has failed.
Returns
-------
stri... | [
"Get",
"user",
"input",
"value",
"from",
"stdin"
] | 1b6d7d1faa2cea13bfaa1f35130f279a0115e686 | https://github.com/lambdalisue/notify/blob/1b6d7d1faa2cea13bfaa1f35130f279a0115e686/src/notify/wizard.py#L22-L49 | train |
south-coast-science/scs_core | src/scs_core/gas/a4_temp_comp.py | A4TempComp.correct | def correct(self, calib, temp, we_t, ae_t):
"""
Compute weC from weT, aeT
"""
if not A4TempComp.in_range(temp):
return None
if self.__algorithm == 1:
return self.__eq1(temp, we_t, ae_t)
if self.__algorithm == 2:
return self.__eq2(temp... | python | def correct(self, calib, temp, we_t, ae_t):
"""
Compute weC from weT, aeT
"""
if not A4TempComp.in_range(temp):
return None
if self.__algorithm == 1:
return self.__eq1(temp, we_t, ae_t)
if self.__algorithm == 2:
return self.__eq2(temp... | [
"def",
"correct",
"(",
"self",
",",
"calib",
",",
"temp",
",",
"we_t",
",",
"ae_t",
")",
":",
"if",
"not",
"A4TempComp",
".",
"in_range",
"(",
"temp",
")",
":",
"return",
"None",
"if",
"self",
".",
"__algorithm",
"==",
"1",
":",
"return",
"self",
"... | Compute weC from weT, aeT | [
"Compute",
"weC",
"from",
"weT",
"aeT"
] | a4152b0bbed6acbbf257e1bba6a912f6ebe578e5 | https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/gas/a4_temp_comp.py#L82-L101 | train |
south-coast-science/scs_core | src/scs_core/gas/a4_temp_comp.py | A4TempComp.cf_t | def cf_t(self, temp):
"""
Compute the linear-interpolated temperature compensation factor.
"""
index = int((temp - A4TempComp.__MIN_TEMP) // A4TempComp.__INTERVAL) # index of start of interval
# on boundary...
if temp % A4TempComp.__INTERVAL == 0:
retu... | python | def cf_t(self, temp):
"""
Compute the linear-interpolated temperature compensation factor.
"""
index = int((temp - A4TempComp.__MIN_TEMP) // A4TempComp.__INTERVAL) # index of start of interval
# on boundary...
if temp % A4TempComp.__INTERVAL == 0:
retu... | [
"def",
"cf_t",
"(",
"self",
",",
"temp",
")",
":",
"index",
"=",
"int",
"(",
"(",
"temp",
"-",
"A4TempComp",
".",
"__MIN_TEMP",
")",
"//",
"A4TempComp",
".",
"__INTERVAL",
")",
"if",
"temp",
"%",
"A4TempComp",
".",
"__INTERVAL",
"==",
"0",
":",
"retu... | Compute the linear-interpolated temperature compensation factor. | [
"Compute",
"the",
"linear",
"-",
"interpolated",
"temperature",
"compensation",
"factor",
"."
] | a4152b0bbed6acbbf257e1bba6a912f6ebe578e5 | https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/gas/a4_temp_comp.py#L152-L175 | train |
cloudbase/python-hnvclient | hnv/common/utils.py | run_once | def run_once(function, state={}, errors={}):
"""A memoization decorator, whose purpose is to cache calls."""
@six.wraps(function)
def _wrapper(*args, **kwargs):
if function in errors:
# Deliberate use of LBYL.
six.reraise(*errors[function])
try:
return st... | python | def run_once(function, state={}, errors={}):
"""A memoization decorator, whose purpose is to cache calls."""
@six.wraps(function)
def _wrapper(*args, **kwargs):
if function in errors:
# Deliberate use of LBYL.
six.reraise(*errors[function])
try:
return st... | [
"def",
"run_once",
"(",
"function",
",",
"state",
"=",
"{",
"}",
",",
"errors",
"=",
"{",
"}",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"function",
")",
"def",
"_wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"function",
"in",
... | A memoization decorator, whose purpose is to cache calls. | [
"A",
"memoization",
"decorator",
"whose",
"purpose",
"is",
"to",
"cache",
"calls",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/utils.py#L187-L204 | train |
cloudbase/python-hnvclient | hnv/common/utils.py | _HNVClient._session | def _session(self):
"""The current session used by the client.
The Session object allows you to persist certain parameters across
requests. It also persists cookies across all requests made from
the Session instance, and will use urllib3's connection pooling.
So if you're making... | python | def _session(self):
"""The current session used by the client.
The Session object allows you to persist certain parameters across
requests. It also persists cookies across all requests made from
the Session instance, and will use urllib3's connection pooling.
So if you're making... | [
"def",
"_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_http_session",
"is",
"None",
":",
"self",
".",
"_http_session",
"=",
"requests",
".",
"Session",
"(",
")",
"self",
".",
"_http_session",
".",
"headers",
".",
"update",
"(",
"self",
".",
"_g... | The current session used by the client.
The Session object allows you to persist certain parameters across
requests. It also persists cookies across all requests made from
the Session instance, and will use urllib3's connection pooling.
So if you're making several requests to the same h... | [
"The",
"current",
"session",
"used",
"by",
"the",
"client",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/utils.py#L59-L79 | train |
cloudbase/python-hnvclient | hnv/common/utils.py | _HNVClient.get_resource | def get_resource(self, path):
"""Getting the required information from the API."""
response = self._http_request(path)
try:
return response.json()
except ValueError:
raise exception.ServiceException("Invalid service response.") | python | def get_resource(self, path):
"""Getting the required information from the API."""
response = self._http_request(path)
try:
return response.json()
except ValueError:
raise exception.ServiceException("Invalid service response.") | [
"def",
"get_resource",
"(",
"self",
",",
"path",
")",
":",
"response",
"=",
"self",
".",
"_http_request",
"(",
"path",
")",
"try",
":",
"return",
"response",
".",
"json",
"(",
")",
"except",
"ValueError",
":",
"raise",
"exception",
".",
"ServiceException",... | Getting the required information from the API. | [
"Getting",
"the",
"required",
"information",
"from",
"the",
"API",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/utils.py#L164-L170 | train |
cloudbase/python-hnvclient | hnv/common/utils.py | _HNVClient.update_resource | def update_resource(self, path, data, if_match=None):
"""Update the required resource."""
response = self._http_request(resource=path, method="PUT", body=data,
if_match=if_match)
try:
return response.json()
except ValueError:
... | python | def update_resource(self, path, data, if_match=None):
"""Update the required resource."""
response = self._http_request(resource=path, method="PUT", body=data,
if_match=if_match)
try:
return response.json()
except ValueError:
... | [
"def",
"update_resource",
"(",
"self",
",",
"path",
",",
"data",
",",
"if_match",
"=",
"None",
")",
":",
"response",
"=",
"self",
".",
"_http_request",
"(",
"resource",
"=",
"path",
",",
"method",
"=",
"\"PUT\"",
",",
"body",
"=",
"data",
",",
"if_matc... | Update the required resource. | [
"Update",
"the",
"required",
"resource",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/utils.py#L172-L179 | train |
Metatab/geoid | geoid/civick.py | GVid.summarize | def summarize(self):
"""Convert all of the values to their max values. This form is used to represent the summary level"""
s = str(self.allval())
return self.parse(s[:2]+ ''.join(['Z']*len(s[2:]))) | python | def summarize(self):
"""Convert all of the values to their max values. This form is used to represent the summary level"""
s = str(self.allval())
return self.parse(s[:2]+ ''.join(['Z']*len(s[2:]))) | [
"def",
"summarize",
"(",
"self",
")",
":",
"s",
"=",
"str",
"(",
"self",
".",
"allval",
"(",
")",
")",
"return",
"self",
".",
"parse",
"(",
"s",
"[",
":",
"2",
"]",
"+",
"''",
".",
"join",
"(",
"[",
"'Z'",
"]",
"*",
"len",
"(",
"s",
"[",
... | Convert all of the values to their max values. This form is used to represent the summary level | [
"Convert",
"all",
"of",
"the",
"values",
"to",
"their",
"max",
"values",
".",
"This",
"form",
"is",
"used",
"to",
"represent",
"the",
"summary",
"level"
] | 4b7769406b00e59376fb6046b42a2f8ed706b33b | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/civick.py#L41-L46 | train |
geophysics-ubonn/reda | lib/reda/utils/filter_config_types.py | _filter_schlumberger | def _filter_schlumberger(configs):
"""Filter Schlumberger configurations
Schlumberger configurations are selected using the following criteria:
* For a given voltage dipole, there need to be at least two current
injections with electrodes located on the left and the right of the
voltage dipole... | python | def _filter_schlumberger(configs):
"""Filter Schlumberger configurations
Schlumberger configurations are selected using the following criteria:
* For a given voltage dipole, there need to be at least two current
injections with electrodes located on the left and the right of the
voltage dipole... | [
"def",
"_filter_schlumberger",
"(",
"configs",
")",
":",
"configs_sorted",
"=",
"np",
".",
"hstack",
"(",
"(",
"np",
".",
"sort",
"(",
"configs",
"[",
":",
",",
"0",
":",
"2",
"]",
",",
"axis",
"=",
"1",
")",
",",
"np",
".",
"sort",
"(",
"configs... | Filter Schlumberger configurations
Schlumberger configurations are selected using the following criteria:
* For a given voltage dipole, there need to be at least two current
injections with electrodes located on the left and the right of the
voltage dipole.
* The distance between the current e... | [
"Filter",
"Schlumberger",
"configurations"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/filter_config_types.py#L17-L97 | train |
geophysics-ubonn/reda | lib/reda/utils/filter_config_types.py | _filter_dipole_dipole | def _filter_dipole_dipole(configs):
"""Filter dipole-dipole configurations
A dipole-dipole configuration is defined using the following criteria:
* equal distance between the two current electrodes and between the two
voltage electrodes
* no overlap of dipoles
Parameters
---... | python | def _filter_dipole_dipole(configs):
"""Filter dipole-dipole configurations
A dipole-dipole configuration is defined using the following criteria:
* equal distance between the two current electrodes and between the two
voltage electrodes
* no overlap of dipoles
Parameters
---... | [
"def",
"_filter_dipole_dipole",
"(",
"configs",
")",
":",
"dist_ab",
"=",
"np",
".",
"abs",
"(",
"configs",
"[",
":",
",",
"0",
"]",
"-",
"configs",
"[",
":",
",",
"1",
"]",
")",
"dist_mn",
"=",
"np",
".",
"abs",
"(",
"configs",
"[",
":",
",",
... | Filter dipole-dipole configurations
A dipole-dipole configuration is defined using the following criteria:
* equal distance between the two current electrodes and between the two
voltage electrodes
* no overlap of dipoles
Parameters
----------
configs: numpy.ndarray
... | [
"Filter",
"dipole",
"-",
"dipole",
"configurations"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/filter_config_types.py#L100-L155 | train |
geophysics-ubonn/reda | lib/reda/utils/filter_config_types.py | _sort_dd_skips | def _sort_dd_skips(configs, dd_indices_all):
"""Given a set of dipole-dipole configurations, sort them according to
their current skip.
Parameters
----------
configs: Nx4 numpy.ndarray
Dipole-Dipole configurations
Returns
-------
dd_configs_sorted: dict
dictionary with ... | python | def _sort_dd_skips(configs, dd_indices_all):
"""Given a set of dipole-dipole configurations, sort them according to
their current skip.
Parameters
----------
configs: Nx4 numpy.ndarray
Dipole-Dipole configurations
Returns
-------
dd_configs_sorted: dict
dictionary with ... | [
"def",
"_sort_dd_skips",
"(",
"configs",
",",
"dd_indices_all",
")",
":",
"config_current_skips",
"=",
"np",
".",
"abs",
"(",
"configs",
"[",
":",
",",
"1",
"]",
"-",
"configs",
"[",
":",
",",
"0",
"]",
")",
"if",
"np",
".",
"all",
"(",
"np",
".",
... | Given a set of dipole-dipole configurations, sort them according to
their current skip.
Parameters
----------
configs: Nx4 numpy.ndarray
Dipole-Dipole configurations
Returns
-------
dd_configs_sorted: dict
dictionary with the skip as keys, and arrays/lists with indices to
... | [
"Given",
"a",
"set",
"of",
"dipole",
"-",
"dipole",
"configurations",
"sort",
"them",
"according",
"to",
"their",
"current",
"skip",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/filter_config_types.py#L158-L189 | train |
geophysics-ubonn/reda | lib/reda/utils/filter_config_types.py | filter | def filter(configs, settings):
"""Main entry function to filtering configuration types
Parameters
----------
configs: Nx4 array
array containing A-B-M-N configurations
settings: dict
'only_types': ['dd', 'other'], # filter only for those types
Returns
-------
dict
... | python | def filter(configs, settings):
"""Main entry function to filtering configuration types
Parameters
----------
configs: Nx4 array
array containing A-B-M-N configurations
settings: dict
'only_types': ['dd', 'other'], # filter only for those types
Returns
-------
dict
... | [
"def",
"filter",
"(",
"configs",
",",
"settings",
")",
":",
"if",
"isinstance",
"(",
"configs",
",",
"pd",
".",
"DataFrame",
")",
":",
"configs",
"=",
"configs",
"[",
"[",
"'a'",
",",
"'b'",
",",
"'m'",
",",
"'n'",
"]",
"]",
".",
"values",
"filter_... | Main entry function to filtering configuration types
Parameters
----------
configs: Nx4 array
array containing A-B-M-N configurations
settings: dict
'only_types': ['dd', 'other'], # filter only for those types
Returns
-------
dict
results dict containing filter res... | [
"Main",
"entry",
"function",
"to",
"filtering",
"configuration",
"types"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/utils/filter_config_types.py#L192-L241 | train |
geophysics-ubonn/reda | lib/reda/exporters/crtomo.py | save_block_to_crt | def save_block_to_crt(filename, group, norrec='all', store_errors=False):
"""Save a dataset to a CRTomo-compatible .crt file
Parameters
----------
filename : string
Output filename
group : pandas.group
Data group
norrec : string
Which data to export Possible values: all|... | python | def save_block_to_crt(filename, group, norrec='all', store_errors=False):
"""Save a dataset to a CRTomo-compatible .crt file
Parameters
----------
filename : string
Output filename
group : pandas.group
Data group
norrec : string
Which data to export Possible values: all|... | [
"def",
"save_block_to_crt",
"(",
"filename",
",",
"group",
",",
"norrec",
"=",
"'all'",
",",
"store_errors",
"=",
"False",
")",
":",
"if",
"norrec",
"!=",
"'all'",
":",
"group",
"=",
"group",
".",
"query",
"(",
"'norrec == \"{0}\"'",
".",
"format",
"(",
... | Save a dataset to a CRTomo-compatible .crt file
Parameters
----------
filename : string
Output filename
group : pandas.group
Data group
norrec : string
Which data to export Possible values: all|nor|rec
store_errors : bool
If true, store errors of the data in a se... | [
"Save",
"a",
"dataset",
"to",
"a",
"CRTomo",
"-",
"compatible",
".",
"crt",
"file"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/exporters/crtomo.py#L7-L53 | train |
geophysics-ubonn/reda | lib/reda/eis/units.py | get_label | def get_label(parameter, ptype, flavor=None, mpl=None):
"""Return the label of a given SIP parameter
Parameters
----------
parameter: string
type of parameter, e.g. rmag|rpha|cre|cim
ptype: string
material|meas. Either return the material property (e.g. resistivity)
or the m... | python | def get_label(parameter, ptype, flavor=None, mpl=None):
"""Return the label of a given SIP parameter
Parameters
----------
parameter: string
type of parameter, e.g. rmag|rpha|cre|cim
ptype: string
material|meas. Either return the material property (e.g. resistivity)
or the m... | [
"def",
"get_label",
"(",
"parameter",
",",
"ptype",
",",
"flavor",
"=",
"None",
",",
"mpl",
"=",
"None",
")",
":",
"if",
"flavor",
"is",
"not",
"None",
":",
"if",
"flavor",
"not",
"in",
"(",
"'latex'",
",",
"'mathml'",
")",
":",
"raise",
"Exception",... | Return the label of a given SIP parameter
Parameters
----------
parameter: string
type of parameter, e.g. rmag|rpha|cre|cim
ptype: string
material|meas. Either return the material property (e.g. resistivity)
or the measurement parameter (e.g., impedance)
flavor: string, opti... | [
"Return",
"the",
"label",
"of",
"a",
"given",
"SIP",
"parameter"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/eis/units.py#L47-L90 | train |
geophysics-ubonn/reda | lib/reda/eis/plots.py | sip_response._add_labels | def _add_labels(self, axes, dtype):
"""Given a 2x2 array of axes, add x and y labels
Parameters
----------
axes: numpy.ndarray, 2x2
A numpy array containing the four principal axes of an SIP plot
dtype: string
Can be either 'rho' or 'r', indicating the ty... | python | def _add_labels(self, axes, dtype):
"""Given a 2x2 array of axes, add x and y labels
Parameters
----------
axes: numpy.ndarray, 2x2
A numpy array containing the four principal axes of an SIP plot
dtype: string
Can be either 'rho' or 'r', indicating the ty... | [
"def",
"_add_labels",
"(",
"self",
",",
"axes",
",",
"dtype",
")",
":",
"for",
"ax",
"in",
"axes",
"[",
"1",
",",
":",
"]",
".",
"flat",
":",
"ax",
".",
"set_xlabel",
"(",
"'frequency [Hz]'",
")",
"if",
"dtype",
"==",
"'rho'",
":",
"axes",
"[",
"... | Given a 2x2 array of axes, add x and y labels
Parameters
----------
axes: numpy.ndarray, 2x2
A numpy array containing the four principal axes of an SIP plot
dtype: string
Can be either 'rho' or 'r', indicating the type of data that is
plotted: 'rho' s... | [
"Given",
"a",
"2x2",
"array",
"of",
"axes",
"add",
"x",
"and",
"y",
"labels"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/eis/plots.py#L78-L108 | train |
geophysics-ubonn/reda | lib/reda/eis/plots.py | multi_sip_response.add | def add(self, response, label=None):
"""add one response object to the list
"""
if not isinstance(response, sip_response.sip_response):
raise Exception(
'can only add sip_reponse.sip_response objects'
)
self.objects.append(response)
if lab... | python | def add(self, response, label=None):
"""add one response object to the list
"""
if not isinstance(response, sip_response.sip_response):
raise Exception(
'can only add sip_reponse.sip_response objects'
)
self.objects.append(response)
if lab... | [
"def",
"add",
"(",
"self",
",",
"response",
",",
"label",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"response",
",",
"sip_response",
".",
"sip_response",
")",
":",
"raise",
"Exception",
"(",
"'can only add sip_reponse.sip_response objects'",
")",
... | add one response object to the list | [
"add",
"one",
"response",
"object",
"to",
"the",
"list"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/eis/plots.py#L358-L370 | train |
geophysics-ubonn/reda | lib/reda/eis/convert.py | split_data | def split_data(data, squeeze=False):
"""
Split 1D or 2D into two parts, using the last axis
Parameters
----------
data:
squeeze : squeeze results to remove unnecessary dimensions
"""
vdata = np.atleast_2d(data)
nr_freqs = int(vdata.shape[1] / 2)
part1 = vdata[:, 0:nr_freqs]
... | python | def split_data(data, squeeze=False):
"""
Split 1D or 2D into two parts, using the last axis
Parameters
----------
data:
squeeze : squeeze results to remove unnecessary dimensions
"""
vdata = np.atleast_2d(data)
nr_freqs = int(vdata.shape[1] / 2)
part1 = vdata[:, 0:nr_freqs]
... | [
"def",
"split_data",
"(",
"data",
",",
"squeeze",
"=",
"False",
")",
":",
"vdata",
"=",
"np",
".",
"atleast_2d",
"(",
"data",
")",
"nr_freqs",
"=",
"int",
"(",
"vdata",
".",
"shape",
"[",
"1",
"]",
"/",
"2",
")",
"part1",
"=",
"vdata",
"[",
":",
... | Split 1D or 2D into two parts, using the last axis
Parameters
----------
data:
squeeze : squeeze results to remove unnecessary dimensions | [
"Split",
"1D",
"or",
"2D",
"into",
"two",
"parts",
"using",
"the",
"last",
"axis"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/eis/convert.py#L14-L30 | train |
geophysics-ubonn/reda | lib/reda/eis/convert.py | convert | def convert(input_format, output_format, data, one_spectrum=False):
"""
Convert from the given format to the requested format
Parameters
----------
input_format : format of input data (parameter 'data')
output_format : format of output data
data : numpy array containing data in specified in... | python | def convert(input_format, output_format, data, one_spectrum=False):
"""
Convert from the given format to the requested format
Parameters
----------
input_format : format of input data (parameter 'data')
output_format : format of output data
data : numpy array containing data in specified in... | [
"def",
"convert",
"(",
"input_format",
",",
"output_format",
",",
"data",
",",
"one_spectrum",
"=",
"False",
")",
":",
"if",
"input_format",
"==",
"output_format",
":",
"return",
"data",
"if",
"input_format",
"not",
"in",
"from_converters",
":",
"raise",
"KeyE... | Convert from the given format to the requested format
Parameters
----------
input_format : format of input data (parameter 'data')
output_format : format of output data
data : numpy array containing data in specified input format
one_spectrum : True|False, the input data comprises one spectrum.... | [
"Convert",
"from",
"the",
"given",
"format",
"to",
"the",
"requested",
"format"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/eis/convert.py#L233-L311 | train |
pennlabs/penn-sdk-python | penn/directory.py | Directory.search | def search(self, params, standardize=False):
"""Get a list of person objects for the given search params.
:param params: Dictionary specifying the query parameters
:param standardize: Whether to standardize names and other features,
currently disabled for backwards compatibility. Cu... | python | def search(self, params, standardize=False):
"""Get a list of person objects for the given search params.
:param params: Dictionary specifying the query parameters
:param standardize: Whether to standardize names and other features,
currently disabled for backwards compatibility. Cu... | [
"def",
"search",
"(",
"self",
",",
"params",
",",
"standardize",
"=",
"False",
")",
":",
"resp",
"=",
"self",
".",
"_request",
"(",
"ENDPOINTS",
"[",
"'SEARCH'",
"]",
",",
"params",
")",
"if",
"not",
"standardize",
":",
"return",
"resp",
"for",
"res",
... | Get a list of person objects for the given search params.
:param params: Dictionary specifying the query parameters
:param standardize: Whether to standardize names and other features,
currently disabled for backwards compatibility. Currently
standardizes names, lowercases email... | [
"Get",
"a",
"list",
"of",
"person",
"objects",
"for",
"the",
"given",
"search",
"params",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/directory.py#L41-L58 | train |
pennlabs/penn-sdk-python | penn/directory.py | Directory.detail_search | def detail_search(self, params, standardize=False):
"""Get a detailed list of person objects for the given search params.
:param params:
Dictionary specifying the query parameters
>>> people_detailed = d.detail_search({'first_name': 'tobias', 'last_name': 'funke'})
"""
... | python | def detail_search(self, params, standardize=False):
"""Get a detailed list of person objects for the given search params.
:param params:
Dictionary specifying the query parameters
>>> people_detailed = d.detail_search({'first_name': 'tobias', 'last_name': 'funke'})
"""
... | [
"def",
"detail_search",
"(",
"self",
",",
"params",
",",
"standardize",
"=",
"False",
")",
":",
"response",
"=",
"self",
".",
"_request",
"(",
"ENDPOINTS",
"[",
"'SEARCH'",
"]",
",",
"params",
")",
"result_data",
"=",
"[",
"]",
"for",
"person",
"in",
"... | Get a detailed list of person objects for the given search params.
:param params:
Dictionary specifying the query parameters
>>> people_detailed = d.detail_search({'first_name': 'tobias', 'last_name': 'funke'}) | [
"Get",
"a",
"detailed",
"list",
"of",
"person",
"objects",
"for",
"the",
"given",
"search",
"params",
"."
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/directory.py#L60-L81 | train |
pennlabs/penn-sdk-python | penn/directory.py | Directory.person_details | def person_details(self, person_id, standardize=False):
"""Get a detailed person object
:param person_id:
String corresponding to the person's id.
>>> instructor = d.person('jhs878sfd03b38b0d463b16320b5e438')
"""
resp = self._request(path.join(ENDPOINTS['DETAILS'], ... | python | def person_details(self, person_id, standardize=False):
"""Get a detailed person object
:param person_id:
String corresponding to the person's id.
>>> instructor = d.person('jhs878sfd03b38b0d463b16320b5e438')
"""
resp = self._request(path.join(ENDPOINTS['DETAILS'], ... | [
"def",
"person_details",
"(",
"self",
",",
"person_id",
",",
"standardize",
"=",
"False",
")",
":",
"resp",
"=",
"self",
".",
"_request",
"(",
"path",
".",
"join",
"(",
"ENDPOINTS",
"[",
"'DETAILS'",
"]",
",",
"person_id",
")",
")",
"if",
"standardize",
... | Get a detailed person object
:param person_id:
String corresponding to the person's id.
>>> instructor = d.person('jhs878sfd03b38b0d463b16320b5e438') | [
"Get",
"a",
"detailed",
"person",
"object"
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/directory.py#L83-L94 | train |
geophysics-ubonn/reda | lib/reda/plotters/pseudoplots.py | plot_ps_extra | def plot_ps_extra(dataobj, key, **kwargs):
"""Create grouped pseudoplots for one or more time steps
Parameters
----------
dataobj: :class:`reda.containers.ERT`
An ERT container with loaded data
key: string
The column name to plot
subquery: string, optional
cbmin: float, opti... | python | def plot_ps_extra(dataobj, key, **kwargs):
"""Create grouped pseudoplots for one or more time steps
Parameters
----------
dataobj: :class:`reda.containers.ERT`
An ERT container with loaded data
key: string
The column name to plot
subquery: string, optional
cbmin: float, opti... | [
"def",
"plot_ps_extra",
"(",
"dataobj",
",",
"key",
",",
"**",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"dataobj",
",",
"pd",
".",
"DataFrame",
")",
":",
"df_raw",
"=",
"dataobj",
"else",
":",
"df_raw",
"=",
"dataobj",
".",
"data",
"if",
"kwargs",
... | Create grouped pseudoplots for one or more time steps
Parameters
----------
dataobj: :class:`reda.containers.ERT`
An ERT container with loaded data
key: string
The column name to plot
subquery: string, optional
cbmin: float, optional
cbmax: float, optional
Examples
... | [
"Create",
"grouped",
"pseudoplots",
"for",
"one",
"or",
"more",
"time",
"steps"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/pseudoplots.py#L314-L385 | train |
fuzeman/PyUPnP | pyupnp/util.py | twisted_absolute_path | def twisted_absolute_path(path, request):
"""Hack to fix twisted not accepting absolute URIs"""
parsed = urlparse.urlparse(request.uri)
if parsed.scheme != '':
path_parts = parsed.path.lstrip('/').split('/')
request.prepath = path_parts[0:1]
request.postpath = path_parts[1:]
... | python | def twisted_absolute_path(path, request):
"""Hack to fix twisted not accepting absolute URIs"""
parsed = urlparse.urlparse(request.uri)
if parsed.scheme != '':
path_parts = parsed.path.lstrip('/').split('/')
request.prepath = path_parts[0:1]
request.postpath = path_parts[1:]
... | [
"def",
"twisted_absolute_path",
"(",
"path",
",",
"request",
")",
":",
"parsed",
"=",
"urlparse",
".",
"urlparse",
"(",
"request",
".",
"uri",
")",
"if",
"parsed",
".",
"scheme",
"!=",
"''",
":",
"path_parts",
"=",
"parsed",
".",
"path",
".",
"lstrip",
... | Hack to fix twisted not accepting absolute URIs | [
"Hack",
"to",
"fix",
"twisted",
"not",
"accepting",
"absolute",
"URIs"
] | 6dea64be299952346a14300ab6cc7dac42736433 | https://github.com/fuzeman/PyUPnP/blob/6dea64be299952346a14300ab6cc7dac42736433/pyupnp/util.py#L24-L32 | train |
geophysics-ubonn/reda | lib/reda/importers/legacy/eit40.py | _add_rhoa | def _add_rhoa(df, spacing):
"""a simple wrapper to compute K factors and add rhoa
"""
df['k'] = redaK.compute_K_analytical(df, spacing=spacing)
df['rho_a'] = df['r'] * df['k']
if 'Zt' in df.columns:
df['rho_a_complex'] = df['Zt'] * df['k']
return df | python | def _add_rhoa(df, spacing):
"""a simple wrapper to compute K factors and add rhoa
"""
df['k'] = redaK.compute_K_analytical(df, spacing=spacing)
df['rho_a'] = df['r'] * df['k']
if 'Zt' in df.columns:
df['rho_a_complex'] = df['Zt'] * df['k']
return df | [
"def",
"_add_rhoa",
"(",
"df",
",",
"spacing",
")",
":",
"df",
"[",
"'k'",
"]",
"=",
"redaK",
".",
"compute_K_analytical",
"(",
"df",
",",
"spacing",
"=",
"spacing",
")",
"df",
"[",
"'rho_a'",
"]",
"=",
"df",
"[",
"'r'",
"]",
"*",
"df",
"[",
"'k'... | a simple wrapper to compute K factors and add rhoa | [
"a",
"simple",
"wrapper",
"to",
"compute",
"K",
"factors",
"and",
"add",
"rhoa"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/importers/legacy/eit40.py#L52-L59 | train |
Metatab/geoid | geoid/util.py | simplify | def simplify(geoids):
"""
Given a list of geoids, reduce it to a simpler set. If there are five or more geoids at one summary level
convert them to a single geoid at the higher level.
:param geoids:
:return:
"""
from collections import defaultdict
aggregated = defaultdict(set)
d ... | python | def simplify(geoids):
"""
Given a list of geoids, reduce it to a simpler set. If there are five or more geoids at one summary level
convert them to a single geoid at the higher level.
:param geoids:
:return:
"""
from collections import defaultdict
aggregated = defaultdict(set)
d ... | [
"def",
"simplify",
"(",
"geoids",
")",
":",
"from",
"collections",
"import",
"defaultdict",
"aggregated",
"=",
"defaultdict",
"(",
"set",
")",
"d",
"=",
"{",
"}",
"for",
"g",
"in",
"geoids",
":",
"if",
"not",
"bool",
"(",
"g",
")",
":",
"continue",
"... | Given a list of geoids, reduce it to a simpler set. If there are five or more geoids at one summary level
convert them to a single geoid at the higher level.
:param geoids:
:return: | [
"Given",
"a",
"list",
"of",
"geoids",
"reduce",
"it",
"to",
"a",
"simpler",
"set",
".",
"If",
"there",
"are",
"five",
"or",
"more",
"geoids",
"at",
"one",
"summary",
"level",
"convert",
"them",
"to",
"a",
"single",
"geoid",
"at",
"the",
"higher",
"leve... | 4b7769406b00e59376fb6046b42a2f8ed706b33b | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/util.py#L3-L38 | train |
Metatab/geoid | geoid/util.py | isimplify | def isimplify(geoids):
"""Iteratively simplify until the set stops getting smaller. """
s0 = list(geoids)
for i in range(10):
s1 = simplify(s0)
if len(s1) == len(s0):
return s1
s0 = s1 | python | def isimplify(geoids):
"""Iteratively simplify until the set stops getting smaller. """
s0 = list(geoids)
for i in range(10):
s1 = simplify(s0)
if len(s1) == len(s0):
return s1
s0 = s1 | [
"def",
"isimplify",
"(",
"geoids",
")",
":",
"s0",
"=",
"list",
"(",
"geoids",
")",
"for",
"i",
"in",
"range",
"(",
"10",
")",
":",
"s1",
"=",
"simplify",
"(",
"s0",
")",
"if",
"len",
"(",
"s1",
")",
"==",
"len",
"(",
"s0",
")",
":",
"return"... | Iteratively simplify until the set stops getting smaller. | [
"Iteratively",
"simplify",
"until",
"the",
"set",
"stops",
"getting",
"smaller",
"."
] | 4b7769406b00e59376fb6046b42a2f8ed706b33b | https://github.com/Metatab/geoid/blob/4b7769406b00e59376fb6046b42a2f8ed706b33b/geoid/util.py#L40-L51 | train |
gtaylor/django-athumb | athumb/management/commands/athumb_regen_field.py | Command.regenerate_thumbs | def regenerate_thumbs(self):
"""
Handle re-generating the thumbnails. All this involves is reading the
original file, then saving the same exact thing. Kind of annoying, but
it's simple.
"""
Model = self.model
instances = Model.objects.all()
num_instances ... | python | def regenerate_thumbs(self):
"""
Handle re-generating the thumbnails. All this involves is reading the
original file, then saving the same exact thing. Kind of annoying, but
it's simple.
"""
Model = self.model
instances = Model.objects.all()
num_instances ... | [
"def",
"regenerate_thumbs",
"(",
"self",
")",
":",
"Model",
"=",
"self",
".",
"model",
"instances",
"=",
"Model",
".",
"objects",
".",
"all",
"(",
")",
"num_instances",
"=",
"instances",
".",
"count",
"(",
")",
"regen_tracker",
"=",
"{",
"}",
"counter",
... | Handle re-generating the thumbnails. All this involves is reading the
original file, then saving the same exact thing. Kind of annoying, but
it's simple. | [
"Handle",
"re",
"-",
"generating",
"the",
"thumbnails",
".",
"All",
"this",
"involves",
"is",
"reading",
"the",
"original",
"file",
"then",
"saving",
"the",
"same",
"exact",
"thing",
".",
"Kind",
"of",
"annoying",
"but",
"it",
"s",
"simple",
"."
] | 69261ace0dff81e33156a54440874456a7b38dfb | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/management/commands/athumb_regen_field.py#L43-L119 | train |
kaustavdm/pyAvroPhonetic | pyavrophonetic/utils/count.py | count_vowels | def count_vowels(text):
"""Count number of occurrences of vowels in a given string"""
count = 0
for i in text:
if i.lower() in config.AVRO_VOWELS:
count += 1
return count | python | def count_vowels(text):
"""Count number of occurrences of vowels in a given string"""
count = 0
for i in text:
if i.lower() in config.AVRO_VOWELS:
count += 1
return count | [
"def",
"count_vowels",
"(",
"text",
")",
":",
"count",
"=",
"0",
"for",
"i",
"in",
"text",
":",
"if",
"i",
".",
"lower",
"(",
")",
"in",
"config",
".",
"AVRO_VOWELS",
":",
"count",
"+=",
"1",
"return",
"count"
] | Count number of occurrences of vowels in a given string | [
"Count",
"number",
"of",
"occurrences",
"of",
"vowels",
"in",
"a",
"given",
"string"
] | 26b7d567d8db025f2cac4de817e716390d7ac337 | https://github.com/kaustavdm/pyAvroPhonetic/blob/26b7d567d8db025f2cac4de817e716390d7ac337/pyavrophonetic/utils/count.py#L31-L37 | train |
kaustavdm/pyAvroPhonetic | pyavrophonetic/utils/count.py | count_consonants | def count_consonants(text):
"""Count number of occurrences of consonants in a given string"""
count = 0
for i in text:
if i.lower() in config.AVRO_CONSONANTS:
count += 1
return count | python | def count_consonants(text):
"""Count number of occurrences of consonants in a given string"""
count = 0
for i in text:
if i.lower() in config.AVRO_CONSONANTS:
count += 1
return count | [
"def",
"count_consonants",
"(",
"text",
")",
":",
"count",
"=",
"0",
"for",
"i",
"in",
"text",
":",
"if",
"i",
".",
"lower",
"(",
")",
"in",
"config",
".",
"AVRO_CONSONANTS",
":",
"count",
"+=",
"1",
"return",
"count"
] | Count number of occurrences of consonants in a given string | [
"Count",
"number",
"of",
"occurrences",
"of",
"consonants",
"in",
"a",
"given",
"string"
] | 26b7d567d8db025f2cac4de817e716390d7ac337 | https://github.com/kaustavdm/pyAvroPhonetic/blob/26b7d567d8db025f2cac4de817e716390d7ac337/pyavrophonetic/utils/count.py#L39-L45 | train |
geophysics-ubonn/reda | lib/reda/plotters/plots2d.py | _pseudodepths_wenner | def _pseudodepths_wenner(configs, spacing=1, grid=None):
"""Given distances between electrodes, compute Wenner pseudo
depths for the provided configuration
The pseudodepth is computed after Roy & Apparao, 1971, as 0.11 times
the distance between the two outermost electrodes. It's not really
clear w... | python | def _pseudodepths_wenner(configs, spacing=1, grid=None):
"""Given distances between electrodes, compute Wenner pseudo
depths for the provided configuration
The pseudodepth is computed after Roy & Apparao, 1971, as 0.11 times
the distance between the two outermost electrodes. It's not really
clear w... | [
"def",
"_pseudodepths_wenner",
"(",
"configs",
",",
"spacing",
"=",
"1",
",",
"grid",
"=",
"None",
")",
":",
"if",
"grid",
"is",
"None",
":",
"xpositions",
"=",
"(",
"configs",
"-",
"1",
")",
"*",
"spacing",
"else",
":",
"xpositions",
"=",
"grid",
".... | Given distances between electrodes, compute Wenner pseudo
depths for the provided configuration
The pseudodepth is computed after Roy & Apparao, 1971, as 0.11 times
the distance between the two outermost electrodes. It's not really
clear why the Wenner depths are different from the Dipole-Dipole
de... | [
"Given",
"distances",
"between",
"electrodes",
"compute",
"Wenner",
"pseudo",
"depths",
"for",
"the",
"provided",
"configuration"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/plots2d.py#L13-L31 | train |
geophysics-ubonn/reda | lib/reda/plotters/plots2d.py | plot_pseudodepths | def plot_pseudodepths(configs, nr_electrodes, spacing=1, grid=None,
ctypes=None, dd_merge=False, **kwargs):
"""Plot pseudodepths for the measurements. If grid is given, then the
actual electrode positions are used, and the parameter 'spacing' is
ignored'
Parameters
----------
... | python | def plot_pseudodepths(configs, nr_electrodes, spacing=1, grid=None,
ctypes=None, dd_merge=False, **kwargs):
"""Plot pseudodepths for the measurements. If grid is given, then the
actual electrode positions are used, and the parameter 'spacing' is
ignored'
Parameters
----------
... | [
"def",
"plot_pseudodepths",
"(",
"configs",
",",
"nr_electrodes",
",",
"spacing",
"=",
"1",
",",
"grid",
"=",
"None",
",",
"ctypes",
"=",
"None",
",",
"dd_merge",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"pseudo_d_functions",
"=",
"{",
"'dd'",
":",
... | Plot pseudodepths for the measurements. If grid is given, then the
actual electrode positions are used, and the parameter 'spacing' is
ignored'
Parameters
----------
configs: :class:`numpy.ndarray`
Nx4 array containing the quadrupoles for different measurements
nr_electrodes: int
... | [
"Plot",
"pseudodepths",
"for",
"the",
"measurements",
".",
"If",
"grid",
"is",
"given",
"then",
"the",
"actual",
"electrode",
"positions",
"are",
"used",
"and",
"the",
"parameter",
"spacing",
"is",
"ignored"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/plots2d.py#L72-L227 | train |
geophysics-ubonn/reda | lib/reda/plotters/plots2d.py | matplot | def matplot(x, y, z, ax=None, colorbar=True, **kwargs):
""" Plot x, y, z as expected with correct axis labels.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from reda.plotters import matplot
>>> a = np.arange(4)
>>> b = np.arange(3) + 3
>>> def sum... | python | def matplot(x, y, z, ax=None, colorbar=True, **kwargs):
""" Plot x, y, z as expected with correct axis labels.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from reda.plotters import matplot
>>> a = np.arange(4)
>>> b = np.arange(3) + 3
>>> def sum... | [
"def",
"matplot",
"(",
"x",
",",
"y",
",",
"z",
",",
"ax",
"=",
"None",
",",
"colorbar",
"=",
"True",
",",
"**",
"kwargs",
")",
":",
"xmin",
"=",
"x",
".",
"min",
"(",
")",
"xmax",
"=",
"x",
".",
"max",
"(",
")",
"dx",
"=",
"np",
".",
"ab... | Plot x, y, z as expected with correct axis labels.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from reda.plotters import matplot
>>> a = np.arange(4)
>>> b = np.arange(3) + 3
>>> def sum(a, b):
... return a + b
>>> x, y = np.meshgrid(a, b)... | [
"Plot",
"x",
"y",
"z",
"as",
"expected",
"with",
"correct",
"axis",
"labels",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/plots2d.py#L417-L470 | train |
frasertweedale/ledgertools | ltlib/xn.py | Xn.summary | def summary(self):
"""Return a string summary of transaction"""
return "\n".join([
"Transaction:",
" When: " + self.date.strftime("%a %d %b %Y"),
" Description: " + self.desc.replace('\n', ' '),
" For amount: {}".format(self.amount),
... | python | def summary(self):
"""Return a string summary of transaction"""
return "\n".join([
"Transaction:",
" When: " + self.date.strftime("%a %d %b %Y"),
" Description: " + self.desc.replace('\n', ' '),
" For amount: {}".format(self.amount),
... | [
"def",
"summary",
"(",
"self",
")",
":",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"\"Transaction:\"",
",",
"\" When: \"",
"+",
"self",
".",
"date",
".",
"strftime",
"(",
"\"%a %d %b %Y\"",
")",
",",
"\" Description: \"",
"+",
"self",
".",
"desc",... | Return a string summary of transaction | [
"Return",
"a",
"string",
"summary",
"of",
"transaction"
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L88-L104 | train |
frasertweedale/ledgertools | ltlib/xn.py | Xn.check | def check(self):
"""Check this transaction for completeness"""
if not self.date:
raise XnDataError("Missing date")
if not self.desc:
raise XnDataError("Missing description")
if not self.dst:
raise XnDataError("No destination accounts")
if not s... | python | def check(self):
"""Check this transaction for completeness"""
if not self.date:
raise XnDataError("Missing date")
if not self.desc:
raise XnDataError("Missing description")
if not self.dst:
raise XnDataError("No destination accounts")
if not s... | [
"def",
"check",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"date",
":",
"raise",
"XnDataError",
"(",
"\"Missing date\"",
")",
"if",
"not",
"self",
".",
"desc",
":",
"raise",
"XnDataError",
"(",
"\"Missing description\"",
")",
"if",
"not",
"self",
"... | Check this transaction for completeness | [
"Check",
"this",
"transaction",
"for",
"completeness"
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L106-L117 | train |
frasertweedale/ledgertools | ltlib/xn.py | Xn.balance | def balance(self):
"""Check this transaction for correctness"""
self.check()
if not sum(map(lambda x: x.amount, self.src)) == -self.amount:
raise XnBalanceError("Sum of source amounts "
"not equal to transaction amount")
if not sum(map(lambda ... | python | def balance(self):
"""Check this transaction for correctness"""
self.check()
if not sum(map(lambda x: x.amount, self.src)) == -self.amount:
raise XnBalanceError("Sum of source amounts "
"not equal to transaction amount")
if not sum(map(lambda ... | [
"def",
"balance",
"(",
"self",
")",
":",
"self",
".",
"check",
"(",
")",
"if",
"not",
"sum",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"amount",
",",
"self",
".",
"src",
")",
")",
"==",
"-",
"self",
".",
"amount",
":",
"raise",
"XnBalanceE... | Check this transaction for correctness | [
"Check",
"this",
"transaction",
"for",
"correctness"
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L119-L128 | train |
frasertweedale/ledgertools | ltlib/xn.py | Xn.match_rules | def match_rules(self, rules):
"""Process this transaction against the given ruleset
Returns a dict of fields with ScoreSet values, which may be empty.
Notably, the rule processing will be shortcircuited if the Xn is
already complete - in this case, None is returned.
"""
... | python | def match_rules(self, rules):
"""Process this transaction against the given ruleset
Returns a dict of fields with ScoreSet values, which may be empty.
Notably, the rule processing will be shortcircuited if the Xn is
already complete - in this case, None is returned.
"""
... | [
"def",
"match_rules",
"(",
"self",
",",
"rules",
")",
":",
"try",
":",
"self",
".",
"check",
"(",
")",
"return",
"None",
"except",
"XnDataError",
":",
"pass",
"scores",
"=",
"{",
"}",
"for",
"r",
"in",
"rules",
":",
"outcomes",
"=",
"r",
".",
"matc... | Process this transaction against the given ruleset
Returns a dict of fields with ScoreSet values, which may be empty.
Notably, the rule processing will be shortcircuited if the Xn is
already complete - in this case, None is returned. | [
"Process",
"this",
"transaction",
"against",
"the",
"given",
"ruleset"
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L130-L166 | train |
frasertweedale/ledgertools | ltlib/xn.py | Xn.complete | def complete(self, uio, dropped=False):
"""Query for all missing information in the transaction"""
if self.dropped and not dropped:
# do nothing for dropped xn, unless specifically told to
return
for end in ['src', 'dst']:
if getattr(self, end):
... | python | def complete(self, uio, dropped=False):
"""Query for all missing information in the transaction"""
if self.dropped and not dropped:
# do nothing for dropped xn, unless specifically told to
return
for end in ['src', 'dst']:
if getattr(self, end):
... | [
"def",
"complete",
"(",
"self",
",",
"uio",
",",
"dropped",
"=",
"False",
")",
":",
"if",
"self",
".",
"dropped",
"and",
"not",
"dropped",
":",
"return",
"for",
"end",
"in",
"[",
"'src'",
",",
"'dst'",
"]",
":",
"if",
"getattr",
"(",
"self",
",",
... | Query for all missing information in the transaction | [
"Query",
"for",
"all",
"missing",
"information",
"in",
"the",
"transaction"
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L312-L351 | train |
frasertweedale/ledgertools | ltlib/xn.py | Xn.process | def process(self, rules, uio, prevxn=None):
"""Matches rules and applies outcomes"""
self.apply_outcomes(self.match_rules(rules), uio, prevxn=prevxn) | python | def process(self, rules, uio, prevxn=None):
"""Matches rules and applies outcomes"""
self.apply_outcomes(self.match_rules(rules), uio, prevxn=prevxn) | [
"def",
"process",
"(",
"self",
",",
"rules",
",",
"uio",
",",
"prevxn",
"=",
"None",
")",
":",
"self",
".",
"apply_outcomes",
"(",
"self",
".",
"match_rules",
"(",
"rules",
")",
",",
"uio",
",",
"prevxn",
"=",
"prevxn",
")"
] | Matches rules and applies outcomes | [
"Matches",
"rules",
"and",
"applies",
"outcomes"
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/xn.py#L353-L355 | train |
geophysics-ubonn/reda | lib/reda/plotters/time_series.py | plot_quadpole_evolution | def plot_quadpole_evolution(dataobj, quadpole, cols, threshold=5,
rolling=False, ax=None):
"""Visualize time-lapse evolution of a single quadropole.
Parameters
----------
dataobj : :py:class:`pandas.DataFrame`
DataFrame containing the data. Please refer to the docume... | python | def plot_quadpole_evolution(dataobj, quadpole, cols, threshold=5,
rolling=False, ax=None):
"""Visualize time-lapse evolution of a single quadropole.
Parameters
----------
dataobj : :py:class:`pandas.DataFrame`
DataFrame containing the data. Please refer to the docume... | [
"def",
"plot_quadpole_evolution",
"(",
"dataobj",
",",
"quadpole",
",",
"cols",
",",
"threshold",
"=",
"5",
",",
"rolling",
"=",
"False",
",",
"ax",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"dataobj",
",",
"pd",
".",
"DataFrame",
")",
":",
"df",... | Visualize time-lapse evolution of a single quadropole.
Parameters
----------
dataobj : :py:class:`pandas.DataFrame`
DataFrame containing the data. Please refer to the documentation for
required columns.
quadpole : list of integers
Electrode numbers of the the quadropole.
col... | [
"Visualize",
"time",
"-",
"lapse",
"evolution",
"of",
"a",
"single",
"quadropole",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/plotters/time_series.py#L9-L93 | train |
shexSpec/grammar | parsers/python/pyshexc/parser_impl/shex_oneofshape_parser.py | ShexOneOfShapeParser.visitSenseFlags | def visitSenseFlags(self, ctx: ShExDocParser.SenseFlagsContext):
""" '!' '^'? | '^' '!'? """
if '!' in ctx.getText():
self.expression.negated = True
if '^' in ctx.getText():
self.expression.inverse = True | python | def visitSenseFlags(self, ctx: ShExDocParser.SenseFlagsContext):
""" '!' '^'? | '^' '!'? """
if '!' in ctx.getText():
self.expression.negated = True
if '^' in ctx.getText():
self.expression.inverse = True | [
"def",
"visitSenseFlags",
"(",
"self",
",",
"ctx",
":",
"ShExDocParser",
".",
"SenseFlagsContext",
")",
":",
"if",
"'!'",
"in",
"ctx",
".",
"getText",
"(",
")",
":",
"self",
".",
"expression",
".",
"negated",
"=",
"True",
"if",
"'^'",
"in",
"ctx",
".",... | '!' '^'? | '^' '!'? | [
"!",
"^",
"?",
"|",
"^",
"!",
"?"
] | 4497cd1f73fa6703bca6e2cb53ba9c120f22e48c | https://github.com/shexSpec/grammar/blob/4497cd1f73fa6703bca6e2cb53ba9c120f22e48c/parsers/python/pyshexc/parser_impl/shex_oneofshape_parser.py#L114-L119 | train |
andy-z/ged4py | ged4py/detail/date.py | CalendarDate.as_tuple | def as_tuple(self):
"""Date as three-tuple of numbers"""
if self._tuple is None:
# extract leading digits from year
year = 9999
if self.year:
m = self.DIGITS.match(self.year)
if m:
year = int(m.group(0))
... | python | def as_tuple(self):
"""Date as three-tuple of numbers"""
if self._tuple is None:
# extract leading digits from year
year = 9999
if self.year:
m = self.DIGITS.match(self.year)
if m:
year = int(m.group(0))
... | [
"def",
"as_tuple",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tuple",
"is",
"None",
":",
"year",
"=",
"9999",
"if",
"self",
".",
"year",
":",
"m",
"=",
"self",
".",
"DIGITS",
".",
"match",
"(",
"self",
".",
"year",
")",
"if",
"m",
":",
"year",... | Date as three-tuple of numbers | [
"Date",
"as",
"three",
"-",
"tuple",
"of",
"numbers"
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/detail/date.py#L142-L157 | train |
andy-z/ged4py | ged4py/detail/date.py | DateValue._cmp_date | def _cmp_date(self):
"""Returns Calendar date used for comparison.
Use the earliest date out of all CalendarDates in this instance,
or some date in the future if there are no CalendarDates (e.g.
when Date is a phrase).
"""
dates = sorted(val for val in self.kw.values()
... | python | def _cmp_date(self):
"""Returns Calendar date used for comparison.
Use the earliest date out of all CalendarDates in this instance,
or some date in the future if there are no CalendarDates (e.g.
when Date is a phrase).
"""
dates = sorted(val for val in self.kw.values()
... | [
"def",
"_cmp_date",
"(",
"self",
")",
":",
"dates",
"=",
"sorted",
"(",
"val",
"for",
"val",
"in",
"self",
".",
"kw",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"val",
",",
"CalendarDate",
")",
")",
"if",
"dates",
":",
"return",
"dates",
"["... | Returns Calendar date used for comparison.
Use the earliest date out of all CalendarDates in this instance,
or some date in the future if there are no CalendarDates (e.g.
when Date is a phrase). | [
"Returns",
"Calendar",
"date",
"used",
"for",
"comparison",
"."
] | d0e0cceaadf0a84cbf052705e3c27303b12e1757 | https://github.com/andy-z/ged4py/blob/d0e0cceaadf0a84cbf052705e3c27303b12e1757/ged4py/detail/date.py#L237-L249 | train |
lekhakpadmanabh/Summarizer | smrzr/better_sentences.py | better_sentences | def better_sentences(func):
"""takes care of some edge cases of sentence
tokenization for cases when websites don't
close sentences properly, usually after
blockquotes, image captions or attributions"""
@wraps(func)
def wrapped(*args):
sentences = func(*args)
new_senten... | python | def better_sentences(func):
"""takes care of some edge cases of sentence
tokenization for cases when websites don't
close sentences properly, usually after
blockquotes, image captions or attributions"""
@wraps(func)
def wrapped(*args):
sentences = func(*args)
new_senten... | [
"def",
"better_sentences",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
")",
":",
"sentences",
"=",
"func",
"(",
"*",
"args",
")",
"new_sentences",
"=",
"[",
"]",
"for",
"i",
",",
"l",
"in",
"enumerate"... | takes care of some edge cases of sentence
tokenization for cases when websites don't
close sentences properly, usually after
blockquotes, image captions or attributions | [
"takes",
"care",
"of",
"some",
"edge",
"cases",
"of",
"sentence",
"tokenization",
"for",
"cases",
"when",
"websites",
"don",
"t",
"close",
"sentences",
"properly",
"usually",
"after",
"blockquotes",
"image",
"captions",
"or",
"attributions"
] | 143456a48217905c720d87331f410e5c8b4e24aa | https://github.com/lekhakpadmanabh/Summarizer/blob/143456a48217905c720d87331f410e5c8b4e24aa/smrzr/better_sentences.py#L3-L26 | train |
south-coast-science/scs_core | src/scs_core/gas/pid_datum.py | PIDDatum.__we_c | def __we_c(cls, calib, tc, temp, we_v):
"""
Compute weC from sensor temperature compensation of weV
"""
offset_v = calib.pid_elc_mv / 1000.0
response_v = we_v - offset_v # remove electronic zero
response_c = tc.correct(temp, response_v) # correct the res... | python | def __we_c(cls, calib, tc, temp, we_v):
"""
Compute weC from sensor temperature compensation of weV
"""
offset_v = calib.pid_elc_mv / 1000.0
response_v = we_v - offset_v # remove electronic zero
response_c = tc.correct(temp, response_v) # correct the res... | [
"def",
"__we_c",
"(",
"cls",
",",
"calib",
",",
"tc",
",",
"temp",
",",
"we_v",
")",
":",
"offset_v",
"=",
"calib",
".",
"pid_elc_mv",
"/",
"1000.0",
"response_v",
"=",
"we_v",
"-",
"offset_v",
"response_c",
"=",
"tc",
".",
"correct",
"(",
"temp",
",... | Compute weC from sensor temperature compensation of weV | [
"Compute",
"weC",
"from",
"sensor",
"temperature",
"compensation",
"of",
"weV"
] | a4152b0bbed6acbbf257e1bba6a912f6ebe578e5 | https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/gas/pid_datum.py#L44-L58 | train |
south-coast-science/scs_core | src/scs_core/gas/pid_datum.py | PIDDatum.__cnc | def __cnc(cls, calib, we_c):
"""
Compute cnc from weC
"""
if we_c is None:
return None
offset_v = calib.pid_elc_mv / 1000.0
response_c = we_c - offset_v # remove electronic zero
cnc = response_c / calib.pid_sens_mv # pid_sens_mv... | python | def __cnc(cls, calib, we_c):
"""
Compute cnc from weC
"""
if we_c is None:
return None
offset_v = calib.pid_elc_mv / 1000.0
response_c = we_c - offset_v # remove electronic zero
cnc = response_c / calib.pid_sens_mv # pid_sens_mv... | [
"def",
"__cnc",
"(",
"cls",
",",
"calib",
",",
"we_c",
")",
":",
"if",
"we_c",
"is",
"None",
":",
"return",
"None",
"offset_v",
"=",
"calib",
".",
"pid_elc_mv",
"/",
"1000.0",
"response_c",
"=",
"we_c",
"-",
"offset_v",
"cnc",
"=",
"response_c",
"/",
... | Compute cnc from weC | [
"Compute",
"cnc",
"from",
"weC"
] | a4152b0bbed6acbbf257e1bba6a912f6ebe578e5 | https://github.com/south-coast-science/scs_core/blob/a4152b0bbed6acbbf257e1bba6a912f6ebe578e5/src/scs_core/gas/pid_datum.py#L62-L74 | train |
cloudbase/python-hnvclient | hnv/common/model.py | Field.add_to_class | def add_to_class(self, model_class):
"""Replace the `Field` attribute with a named `_FieldDescriptor`.
.. note::
This method is called during construction of the `Model`.
"""
model_class._meta.add_field(self)
setattr(model_class, self.name, _FieldDescriptor(self)) | python | def add_to_class(self, model_class):
"""Replace the `Field` attribute with a named `_FieldDescriptor`.
.. note::
This method is called during construction of the `Model`.
"""
model_class._meta.add_field(self)
setattr(model_class, self.name, _FieldDescriptor(self)) | [
"def",
"add_to_class",
"(",
"self",
",",
"model_class",
")",
":",
"model_class",
".",
"_meta",
".",
"add_field",
"(",
"self",
")",
"setattr",
"(",
"model_class",
",",
"self",
".",
"name",
",",
"_FieldDescriptor",
"(",
"self",
")",
")"
] | Replace the `Field` attribute with a named `_FieldDescriptor`.
.. note::
This method is called during construction of the `Model`. | [
"Replace",
"the",
"Field",
"attribute",
"with",
"a",
"named",
"_FieldDescriptor",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/model.py#L126-L133 | train |
cloudbase/python-hnvclient | hnv/common/model.py | _ModelOptions.add_field | def add_field(self, field):
"""Add the received field to the model."""
self.remove_field(field.name)
self._fields[field.name] = field
if field.default is not None:
if six.callable(field.default):
self._default_callables[field.key] = field.default
... | python | def add_field(self, field):
"""Add the received field to the model."""
self.remove_field(field.name)
self._fields[field.name] = field
if field.default is not None:
if six.callable(field.default):
self._default_callables[field.key] = field.default
... | [
"def",
"add_field",
"(",
"self",
",",
"field",
")",
":",
"self",
".",
"remove_field",
"(",
"field",
".",
"name",
")",
"self",
".",
"_fields",
"[",
"field",
".",
"name",
"]",
"=",
"field",
"if",
"field",
".",
"default",
"is",
"not",
"None",
":",
"if... | Add the received field to the model. | [
"Add",
"the",
"received",
"field",
"to",
"the",
"model",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/model.py#L157-L166 | train |
cloudbase/python-hnvclient | hnv/common/model.py | _ModelOptions.remove_field | def remove_field(self, field_name):
"""Remove the field with the received field name from model."""
field = self._fields.pop(field_name, None)
if field is not None and field.default is not None:
if six.callable(field.default):
self._default_callables.pop(field.key, No... | python | def remove_field(self, field_name):
"""Remove the field with the received field name from model."""
field = self._fields.pop(field_name, None)
if field is not None and field.default is not None:
if six.callable(field.default):
self._default_callables.pop(field.key, No... | [
"def",
"remove_field",
"(",
"self",
",",
"field_name",
")",
":",
"field",
"=",
"self",
".",
"_fields",
".",
"pop",
"(",
"field_name",
",",
"None",
")",
"if",
"field",
"is",
"not",
"None",
"and",
"field",
".",
"default",
"is",
"not",
"None",
":",
"if"... | Remove the field with the received field name from model. | [
"Remove",
"the",
"field",
"with",
"the",
"received",
"field",
"name",
"from",
"model",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/model.py#L168-L175 | train |
cloudbase/python-hnvclient | hnv/common/model.py | _ModelOptions.get_defaults | def get_defaults(self):
"""Get a dictionary that contains all the available defaults."""
defaults = self._defaults.copy()
for field_key, default in self._default_callables.items():
defaults[field_key] = default()
return defaults | python | def get_defaults(self):
"""Get a dictionary that contains all the available defaults."""
defaults = self._defaults.copy()
for field_key, default in self._default_callables.items():
defaults[field_key] = default()
return defaults | [
"def",
"get_defaults",
"(",
"self",
")",
":",
"defaults",
"=",
"self",
".",
"_defaults",
".",
"copy",
"(",
")",
"for",
"field_key",
",",
"default",
"in",
"self",
".",
"_default_callables",
".",
"items",
"(",
")",
":",
"defaults",
"[",
"field_key",
"]",
... | Get a dictionary that contains all the available defaults. | [
"Get",
"a",
"dictionary",
"that",
"contains",
"all",
"the",
"available",
"defaults",
"."
] | b019452af01db22629809b8930357a2ebf6494be | https://github.com/cloudbase/python-hnvclient/blob/b019452af01db22629809b8930357a2ebf6494be/hnv/common/model.py#L177-L182 | train |
newfies-dialer/python-msspeak | msspeak/msspeak.py | MSSpeak.speak | def speak(self, textstr, lang='en-US', gender='female', format='riff-16khz-16bit-mono-pcm'):
"""
Run will call Microsoft Translate API and and produce audio
"""
# print("speak(textstr=%s, lang=%s, gender=%s, format=%s)" % (textstr, lang, gender, format))
concatkey = '%s-%s-%s-%s'... | python | def speak(self, textstr, lang='en-US', gender='female', format='riff-16khz-16bit-mono-pcm'):
"""
Run will call Microsoft Translate API and and produce audio
"""
# print("speak(textstr=%s, lang=%s, gender=%s, format=%s)" % (textstr, lang, gender, format))
concatkey = '%s-%s-%s-%s'... | [
"def",
"speak",
"(",
"self",
",",
"textstr",
",",
"lang",
"=",
"'en-US'",
",",
"gender",
"=",
"'female'",
",",
"format",
"=",
"'riff-16khz-16bit-mono-pcm'",
")",
":",
"concatkey",
"=",
"'%s-%s-%s-%s'",
"%",
"(",
"textstr",
",",
"lang",
".",
"lower",
"(",
... | Run will call Microsoft Translate API and and produce audio | [
"Run",
"will",
"call",
"Microsoft",
"Translate",
"API",
"and",
"and",
"produce",
"audio"
] | 106475122be73df152865c4fe6e9388caf974085 | https://github.com/newfies-dialer/python-msspeak/blob/106475122be73df152865c4fe6e9388caf974085/msspeak/msspeak.py#L193-L210 | train |
lambdalisue/notify | src/notify/executor.py | call | def call(args):
"""
Call terminal command and return exit_code and stdout
Parameters
----------
args : list
A command and arguments list
Returns
-------
list : [exit_code, stdout]
exit_code indicate the exit code of the command and stdout indicate the
output of ... | python | def call(args):
"""
Call terminal command and return exit_code and stdout
Parameters
----------
args : list
A command and arguments list
Returns
-------
list : [exit_code, stdout]
exit_code indicate the exit code of the command and stdout indicate the
output of ... | [
"def",
"call",
"(",
"args",
")",
":",
"b",
"=",
"StringIO",
"(",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"encoding",
"=",
"getattr",
... | Call terminal command and return exit_code and stdout
Parameters
----------
args : list
A command and arguments list
Returns
-------
list : [exit_code, stdout]
exit_code indicate the exit code of the command and stdout indicate the
output of the command | [
"Call",
"terminal",
"command",
"and",
"return",
"exit_code",
"and",
"stdout"
] | 1b6d7d1faa2cea13bfaa1f35130f279a0115e686 | https://github.com/lambdalisue/notify/blob/1b6d7d1faa2cea13bfaa1f35130f279a0115e686/src/notify/executor.py#L17-L51 | train |
lambdalisue/notify | src/notify/executor.py | get_command_str | def get_command_str(args):
"""
Get terminal command string from list of command and arguments
Parameters
----------
args : list
A command and arguments list (unicode list)
Returns
-------
str
A string indicate terminal command
"""
single_quote = "'"
double_q... | python | def get_command_str(args):
"""
Get terminal command string from list of command and arguments
Parameters
----------
args : list
A command and arguments list (unicode list)
Returns
-------
str
A string indicate terminal command
"""
single_quote = "'"
double_q... | [
"def",
"get_command_str",
"(",
"args",
")",
":",
"single_quote",
"=",
"\"'\"",
"double_quote",
"=",
"'\"'",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"\" \"",
"in",
"value",
"and",
"double_quote",
"not",
"in",
"value",
":"... | Get terminal command string from list of command and arguments
Parameters
----------
args : list
A command and arguments list (unicode list)
Returns
-------
str
A string indicate terminal command | [
"Get",
"terminal",
"command",
"string",
"from",
"list",
"of",
"command",
"and",
"arguments"
] | 1b6d7d1faa2cea13bfaa1f35130f279a0115e686 | https://github.com/lambdalisue/notify/blob/1b6d7d1faa2cea13bfaa1f35130f279a0115e686/src/notify/executor.py#L53-L74 | train |
gtaylor/django-athumb | athumb/upload_handlers/gunicorn_eventlet.py | EventletTmpFileUploadHandler.receive_data_chunk | def receive_data_chunk(self, raw_data, start):
"""
Over-ridden method to circumvent the worker timeouts on large uploads.
"""
self.file.write(raw_data)
# CHANGED: This un-hangs us long enough to keep things rolling.
eventlet.sleep(0) | python | def receive_data_chunk(self, raw_data, start):
"""
Over-ridden method to circumvent the worker timeouts on large uploads.
"""
self.file.write(raw_data)
# CHANGED: This un-hangs us long enough to keep things rolling.
eventlet.sleep(0) | [
"def",
"receive_data_chunk",
"(",
"self",
",",
"raw_data",
",",
"start",
")",
":",
"self",
".",
"file",
".",
"write",
"(",
"raw_data",
")",
"eventlet",
".",
"sleep",
"(",
"0",
")"
] | Over-ridden method to circumvent the worker timeouts on large uploads. | [
"Over",
"-",
"ridden",
"method",
"to",
"circumvent",
"the",
"worker",
"timeouts",
"on",
"large",
"uploads",
"."
] | 69261ace0dff81e33156a54440874456a7b38dfb | https://github.com/gtaylor/django-athumb/blob/69261ace0dff81e33156a54440874456a7b38dfb/athumb/upload_handlers/gunicorn_eventlet.py#L15-L21 | train |
pennlabs/penn-sdk-python | penn/transit.py | Transit.stoptimes | def stoptimes(self, start_date, end_date):
"""Return all stop times in the date range
:param start_date:
The starting date for the query.
:param end_date:
The end date for the query.
>>> import datetime
>>> today = datetime.date.today()
>>> trans.... | python | def stoptimes(self, start_date, end_date):
"""Return all stop times in the date range
:param start_date:
The starting date for the query.
:param end_date:
The end date for the query.
>>> import datetime
>>> today = datetime.date.today()
>>> trans.... | [
"def",
"stoptimes",
"(",
"self",
",",
"start_date",
",",
"end_date",
")",
":",
"params",
"=",
"{",
"'start'",
":",
"self",
".",
"format_date",
"(",
"start_date",
")",
",",
"'end'",
":",
"self",
".",
"format_date",
"(",
"end_date",
")",
"}",
"response",
... | Return all stop times in the date range
:param start_date:
The starting date for the query.
:param end_date:
The end date for the query.
>>> import datetime
>>> today = datetime.date.today()
>>> trans.stoptimes(today - datetime.timedelta(days=1), today) | [
"Return",
"all",
"stop",
"times",
"in",
"the",
"date",
"range"
] | 31ff12c20d69438d63bc7a796f83ce4f4c828396 | https://github.com/pennlabs/penn-sdk-python/blob/31ff12c20d69438d63bc7a796f83ce4f4c828396/penn/transit.py#L115-L131 | train |
geophysics-ubonn/reda | lib/reda/main/logger.py | LoggingClass.setup_logger | def setup_logger(self):
"""Setup a logger
"""
self.log_list = []
handler = ListHandler(self.log_list)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger = logging.getLogger()
... | python | def setup_logger(self):
"""Setup a logger
"""
self.log_list = []
handler = ListHandler(self.log_list)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger = logging.getLogger()
... | [
"def",
"setup_logger",
"(",
"self",
")",
":",
"self",
".",
"log_list",
"=",
"[",
"]",
"handler",
"=",
"ListHandler",
"(",
"self",
".",
"log_list",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s - %(name)s - %(levelname)s - %(message)s'",
... | Setup a logger | [
"Setup",
"a",
"logger"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/main/logger.py#L30-L46 | train |
frasertweedale/ledgertools | ltlib/balance.py | match_to_dict | def match_to_dict(match):
"""Convert a match object into a dict.
Values are:
indent: amount of indentation of this [sub]account
parent: the parent dict (None)
account_fragment: account name fragment
balance: decimal.Decimal balance
children: sub-accounts ([])
"""
... | python | def match_to_dict(match):
"""Convert a match object into a dict.
Values are:
indent: amount of indentation of this [sub]account
parent: the parent dict (None)
account_fragment: account name fragment
balance: decimal.Decimal balance
children: sub-accounts ([])
"""
... | [
"def",
"match_to_dict",
"(",
"match",
")",
":",
"balance",
",",
"indent",
",",
"account_fragment",
"=",
"match",
".",
"group",
"(",
"1",
",",
"2",
",",
"3",
")",
"return",
"{",
"'balance'",
":",
"decimal",
".",
"Decimal",
"(",
"balance",
")",
",",
"'... | Convert a match object into a dict.
Values are:
indent: amount of indentation of this [sub]account
parent: the parent dict (None)
account_fragment: account name fragment
balance: decimal.Decimal balance
children: sub-accounts ([]) | [
"Convert",
"a",
"match",
"object",
"into",
"a",
"dict",
"."
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/balance.py#L24-L41 | train |
frasertweedale/ledgertools | ltlib/balance.py | balance | def balance(output):
"""Convert `ledger balance` output into an hierarchical data structure."""
lines = map(pattern.search, output.splitlines())
stack = []
top = []
for item in map(match_to_dict, itertools.takewhile(lambda x: x, lines)):
# pop items off stack while current item has indent <... | python | def balance(output):
"""Convert `ledger balance` output into an hierarchical data structure."""
lines = map(pattern.search, output.splitlines())
stack = []
top = []
for item in map(match_to_dict, itertools.takewhile(lambda x: x, lines)):
# pop items off stack while current item has indent <... | [
"def",
"balance",
"(",
"output",
")",
":",
"lines",
"=",
"map",
"(",
"pattern",
".",
"search",
",",
"output",
".",
"splitlines",
"(",
")",
")",
"stack",
"=",
"[",
"]",
"top",
"=",
"[",
"]",
"for",
"item",
"in",
"map",
"(",
"match_to_dict",
",",
"... | Convert `ledger balance` output into an hierarchical data structure. | [
"Convert",
"ledger",
"balance",
"output",
"into",
"an",
"hierarchical",
"data",
"structure",
"."
] | a695f8667d72253e5448693c12f0282d09902aaa | https://github.com/frasertweedale/ledgertools/blob/a695f8667d72253e5448693c12f0282d09902aaa/ltlib/balance.py#L44-L64 | train |
kaustavdm/pyAvroPhonetic | pyavrophonetic/utils/validate.py | is_punctuation | def is_punctuation(text):
"""Check if given string is a punctuation"""
return not (text.lower() in config.AVRO_VOWELS or
text.lower() in config.AVRO_CONSONANTS) | python | def is_punctuation(text):
"""Check if given string is a punctuation"""
return not (text.lower() in config.AVRO_VOWELS or
text.lower() in config.AVRO_CONSONANTS) | [
"def",
"is_punctuation",
"(",
"text",
")",
":",
"return",
"not",
"(",
"text",
".",
"lower",
"(",
")",
"in",
"config",
".",
"AVRO_VOWELS",
"or",
"text",
".",
"lower",
"(",
")",
"in",
"config",
".",
"AVRO_CONSONANTS",
")"
] | Check if given string is a punctuation | [
"Check",
"if",
"given",
"string",
"is",
"a",
"punctuation"
] | 26b7d567d8db025f2cac4de817e716390d7ac337 | https://github.com/kaustavdm/pyAvroPhonetic/blob/26b7d567d8db025f2cac4de817e716390d7ac337/pyavrophonetic/utils/validate.py#L43-L46 | train |
kaustavdm/pyAvroPhonetic | pyavrophonetic/utils/validate.py | is_exact | def is_exact(needle, haystack, start, end, matchnot):
"""Check exact occurrence of needle in haystack"""
return ((start >= 0 and end < len(haystack) and
haystack[start:end] == needle) ^ matchnot) | python | def is_exact(needle, haystack, start, end, matchnot):
"""Check exact occurrence of needle in haystack"""
return ((start >= 0 and end < len(haystack) and
haystack[start:end] == needle) ^ matchnot) | [
"def",
"is_exact",
"(",
"needle",
",",
"haystack",
",",
"start",
",",
"end",
",",
"matchnot",
")",
":",
"return",
"(",
"(",
"start",
">=",
"0",
"and",
"end",
"<",
"len",
"(",
"haystack",
")",
"and",
"haystack",
"[",
"start",
":",
"end",
"]",
"==",
... | Check exact occurrence of needle in haystack | [
"Check",
"exact",
"occurrence",
"of",
"needle",
"in",
"haystack"
] | 26b7d567d8db025f2cac4de817e716390d7ac337 | https://github.com/kaustavdm/pyAvroPhonetic/blob/26b7d567d8db025f2cac4de817e716390d7ac337/pyavrophonetic/utils/validate.py#L52-L55 | train |
kaustavdm/pyAvroPhonetic | pyavrophonetic/utils/validate.py | fix_string_case | def fix_string_case(text):
"""Converts case-insensitive characters to lower case
Case-sensitive characters as defined in config.AVRO_CASESENSITIVES
retain their case, but others are converted to their lowercase
equivalents. The result is a string with phonetic-compatible case
which will the parser ... | python | def fix_string_case(text):
"""Converts case-insensitive characters to lower case
Case-sensitive characters as defined in config.AVRO_CASESENSITIVES
retain their case, but others are converted to their lowercase
equivalents. The result is a string with phonetic-compatible case
which will the parser ... | [
"def",
"fix_string_case",
"(",
"text",
")",
":",
"fixed",
"=",
"[",
"]",
"for",
"i",
"in",
"text",
":",
"if",
"is_case_sensitive",
"(",
"i",
")",
":",
"fixed",
".",
"append",
"(",
"i",
")",
"else",
":",
"fixed",
".",
"append",
"(",
"i",
".",
"low... | Converts case-insensitive characters to lower case
Case-sensitive characters as defined in config.AVRO_CASESENSITIVES
retain their case, but others are converted to their lowercase
equivalents. The result is a string with phonetic-compatible case
which will the parser will understand without confusion. | [
"Converts",
"case",
"-",
"insensitive",
"characters",
"to",
"lower",
"case"
] | 26b7d567d8db025f2cac4de817e716390d7ac337 | https://github.com/kaustavdm/pyAvroPhonetic/blob/26b7d567d8db025f2cac4de817e716390d7ac337/pyavrophonetic/utils/validate.py#L57-L71 | train |
geophysics-ubonn/reda | lib/reda/configs/configManager.py | ConfigManager._crmod_to_abmn | def _crmod_to_abmn(self, configs):
"""convert crmod-style configurations to a Nx4 array
CRMod-style configurations merge A and B, and M and N, electrode
numbers into one large integer each:
.. math ::
AB = A \cdot 10^4 + B
MN = M \cdot 10^4 + N
Parame... | python | def _crmod_to_abmn(self, configs):
"""convert crmod-style configurations to a Nx4 array
CRMod-style configurations merge A and B, and M and N, electrode
numbers into one large integer each:
.. math ::
AB = A \cdot 10^4 + B
MN = M \cdot 10^4 + N
Parame... | [
"def",
"_crmod_to_abmn",
"(",
"self",
",",
"configs",
")",
":",
"A",
"=",
"configs",
"[",
":",
",",
"0",
"]",
"%",
"1e4",
"B",
"=",
"np",
".",
"floor",
"(",
"configs",
"[",
":",
",",
"0",
"]",
"/",
"1e4",
")",
".",
"astype",
"(",
"int",
")",
... | convert crmod-style configurations to a Nx4 array
CRMod-style configurations merge A and B, and M and N, electrode
numbers into one large integer each:
.. math ::
AB = A \cdot 10^4 + B
MN = M \cdot 10^4 + N
Parameters
----------
configs: numpy... | [
"convert",
"crmod",
"-",
"style",
"configurations",
"to",
"a",
"Nx4",
"array"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L54-L93 | train |
geophysics-ubonn/reda | lib/reda/configs/configManager.py | ConfigManager.load_crmod_config | def load_crmod_config(self, filename):
"""Load a CRMod configuration file
Parameters
----------
filename: string
absolute or relative path to a crmod config.dat file
"""
with open(filename, 'r') as fid:
nr_of_configs = int(fid.readline().strip())... | python | def load_crmod_config(self, filename):
"""Load a CRMod configuration file
Parameters
----------
filename: string
absolute or relative path to a crmod config.dat file
"""
with open(filename, 'r') as fid:
nr_of_configs = int(fid.readline().strip())... | [
"def",
"load_crmod_config",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fid",
":",
"nr_of_configs",
"=",
"int",
"(",
"fid",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
")",
"configs",
"=",
... | Load a CRMod configuration file
Parameters
----------
filename: string
absolute or relative path to a crmod config.dat file | [
"Load",
"a",
"CRMod",
"configuration",
"file"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L101-L119 | train |
geophysics-ubonn/reda | lib/reda/configs/configManager.py | ConfigManager._get_crmod_abmn | def _get_crmod_abmn(self):
"""return a Nx2 array with the measurement configurations formatted
CRTomo style
"""
ABMN = np.vstack((
self.configs[:, 0] * 1e4 + self.configs[:, 1],
self.configs[:, 2] * 1e4 + self.configs[:, 3],
)).T.astype(int)
return... | python | def _get_crmod_abmn(self):
"""return a Nx2 array with the measurement configurations formatted
CRTomo style
"""
ABMN = np.vstack((
self.configs[:, 0] * 1e4 + self.configs[:, 1],
self.configs[:, 2] * 1e4 + self.configs[:, 3],
)).T.astype(int)
return... | [
"def",
"_get_crmod_abmn",
"(",
"self",
")",
":",
"ABMN",
"=",
"np",
".",
"vstack",
"(",
"(",
"self",
".",
"configs",
"[",
":",
",",
"0",
"]",
"*",
"1e4",
"+",
"self",
".",
"configs",
"[",
":",
",",
"1",
"]",
",",
"self",
".",
"configs",
"[",
... | return a Nx2 array with the measurement configurations formatted
CRTomo style | [
"return",
"a",
"Nx2",
"array",
"with",
"the",
"measurement",
"configurations",
"formatted",
"CRTomo",
"style"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L156-L164 | train |
geophysics-ubonn/reda | lib/reda/configs/configManager.py | ConfigManager.write_crmod_volt | def write_crmod_volt(self, filename, mid):
"""Write the measurements to the output file in the volt.dat file
format that can be read by CRTomo.
Parameters
----------
filename: string
output filename
mid: int or [int, int]
measurement ids of magnit... | python | def write_crmod_volt(self, filename, mid):
"""Write the measurements to the output file in the volt.dat file
format that can be read by CRTomo.
Parameters
----------
filename: string
output filename
mid: int or [int, int]
measurement ids of magnit... | [
"def",
"write_crmod_volt",
"(",
"self",
",",
"filename",
",",
"mid",
")",
":",
"ABMN",
"=",
"self",
".",
"_get_crmod_abmn",
"(",
")",
"if",
"isinstance",
"(",
"mid",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"mag_data",
"=",
"self",
".",
"measur... | Write the measurements to the output file in the volt.dat file
format that can be read by CRTomo.
Parameters
----------
filename: string
output filename
mid: int or [int, int]
measurement ids of magnitude and phase measurements. If only one ID
... | [
"Write",
"the",
"measurements",
"to",
"the",
"output",
"file",
"in",
"the",
"volt",
".",
"dat",
"file",
"format",
"that",
"can",
"be",
"read",
"by",
"CRTomo",
"."
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L166-L196 | train |
geophysics-ubonn/reda | lib/reda/configs/configManager.py | ConfigManager.write_crmod_config | def write_crmod_config(self, filename):
"""Write the configurations to a configuration file in the CRMod format
All configurations are merged into one previor to writing to file
Parameters
----------
filename: string
absolute or relative path to output filename (usua... | python | def write_crmod_config(self, filename):
"""Write the configurations to a configuration file in the CRMod format
All configurations are merged into one previor to writing to file
Parameters
----------
filename: string
absolute or relative path to output filename (usua... | [
"def",
"write_crmod_config",
"(",
"self",
",",
"filename",
")",
":",
"ABMN",
"=",
"self",
".",
"_get_crmod_abmn",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"fid",
":",
"fid",
".",
"write",
"(",
"bytes",
"(",
"'{0}\\n'",
".",
... | Write the configurations to a configuration file in the CRMod format
All configurations are merged into one previor to writing to file
Parameters
----------
filename: string
absolute or relative path to output filename (usually config.dat) | [
"Write",
"the",
"configurations",
"to",
"a",
"configuration",
"file",
"in",
"the",
"CRMod",
"format",
"All",
"configurations",
"are",
"merged",
"into",
"one",
"previor",
"to",
"writing",
"to",
"file"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L198-L214 | train |
geophysics-ubonn/reda | lib/reda/configs/configManager.py | ConfigManager.gen_dipole_dipole | def gen_dipole_dipole(self,
skipc,
skipv=None,
stepc=1,
stepv=1,
nr_voltage_dipoles=10,
before_current=False,
start_skip=0,
... | python | def gen_dipole_dipole(self,
skipc,
skipv=None,
stepc=1,
stepv=1,
nr_voltage_dipoles=10,
before_current=False,
start_skip=0,
... | [
"def",
"gen_dipole_dipole",
"(",
"self",
",",
"skipc",
",",
"skipv",
"=",
"None",
",",
"stepc",
"=",
"1",
",",
"stepv",
"=",
"1",
",",
"nr_voltage_dipoles",
"=",
"10",
",",
"before_current",
"=",
"False",
",",
"start_skip",
"=",
"0",
",",
"N",
"=",
"... | Generate dipole-dipole configurations
Parameters
----------
skipc: int
number of electrode positions that are skipped between electrodes
of a given dipole
skipv: int
steplength between subsequent voltage dipoles. A steplength of 0
will pro... | [
"Generate",
"dipole",
"-",
"dipole",
"configurations"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L216-L311 | train |
geophysics-ubonn/reda | lib/reda/configs/configManager.py | ConfigManager.gen_gradient | def gen_gradient(self, skip=0, step=1, vskip=0, vstep=1):
"""Generate gradient measurements
Parameters
----------
skip: int
distance between current electrodes
step: int
steplength between subsequent current dipoles
vskip: int
distance... | python | def gen_gradient(self, skip=0, step=1, vskip=0, vstep=1):
"""Generate gradient measurements
Parameters
----------
skip: int
distance between current electrodes
step: int
steplength between subsequent current dipoles
vskip: int
distance... | [
"def",
"gen_gradient",
"(",
"self",
",",
"skip",
"=",
"0",
",",
"step",
"=",
"1",
",",
"vskip",
"=",
"0",
",",
"vstep",
"=",
"1",
")",
":",
"N",
"=",
"self",
".",
"nr_electrodes",
"quadpoles",
"=",
"[",
"]",
"for",
"a",
"in",
"range",
"(",
"1",... | Generate gradient measurements
Parameters
----------
skip: int
distance between current electrodes
step: int
steplength between subsequent current dipoles
vskip: int
distance between voltage electrodes
vstep: int
steplength... | [
"Generate",
"gradient",
"measurements"
] | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L313-L341 | train |
geophysics-ubonn/reda | lib/reda/configs/configManager.py | ConfigManager.remove_duplicates | def remove_duplicates(self, configs=None):
"""remove duplicate entries from 4-point configurations. If no
configurations are provided, then use self.configs. Unique
configurations are only returned if configs is not None.
Parameters
----------
configs: Nx4 numpy.ndarray,... | python | def remove_duplicates(self, configs=None):
"""remove duplicate entries from 4-point configurations. If no
configurations are provided, then use self.configs. Unique
configurations are only returned if configs is not None.
Parameters
----------
configs: Nx4 numpy.ndarray,... | [
"def",
"remove_duplicates",
"(",
"self",
",",
"configs",
"=",
"None",
")",
":",
"if",
"configs",
"is",
"None",
":",
"c",
"=",
"self",
".",
"configs",
"else",
":",
"c",
"=",
"configs",
"struct",
"=",
"c",
".",
"view",
"(",
"c",
".",
"dtype",
".",
... | remove duplicate entries from 4-point configurations. If no
configurations are provided, then use self.configs. Unique
configurations are only returned if configs is not None.
Parameters
----------
configs: Nx4 numpy.ndarray, optional
remove duplicates from these con... | [
"remove",
"duplicate",
"entries",
"from",
"4",
"-",
"point",
"configurations",
".",
"If",
"no",
"configurations",
"are",
"provided",
"then",
"use",
"self",
".",
"configs",
".",
"Unique",
"configurations",
"are",
"only",
"returned",
"if",
"configs",
"is",
"not"... | 46a939729e40c7c4723315c03679c40761152e9e | https://github.com/geophysics-ubonn/reda/blob/46a939729e40c7c4723315c03679c40761152e9e/lib/reda/configs/configManager.py#L431-L457 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.