repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
royi1000/py-libhdate | hdate/zmanim.py | Zmanim._havdalah_datetime | def _havdalah_datetime(self):
"""Compute the havdalah time based on settings."""
if self.havdalah_offset == 0:
return self.zmanim["three_stars"]
# Otherwise, use the offset.
return (self.zmanim["sunset"]
+ dt.timedelta(minutes=self.havdalah_offset)) | python | def _havdalah_datetime(self):
"""Compute the havdalah time based on settings."""
if self.havdalah_offset == 0:
return self.zmanim["three_stars"]
# Otherwise, use the offset.
return (self.zmanim["sunset"]
+ dt.timedelta(minutes=self.havdalah_offset)) | [
"def",
"_havdalah_datetime",
"(",
"self",
")",
":",
"if",
"self",
".",
"havdalah_offset",
"==",
"0",
":",
"return",
"self",
".",
"zmanim",
"[",
"\"three_stars\"",
"]",
"# Otherwise, use the offset.",
"return",
"(",
"self",
".",
"zmanim",
"[",
"\"sunset\"",
"]"... | Compute the havdalah time based on settings. | [
"Compute",
"the",
"havdalah",
"time",
"based",
"on",
"settings",
"."
] | train | https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/zmanim.py#L93-L99 |
royi1000/py-libhdate | hdate/zmanim.py | Zmanim.havdalah | def havdalah(self):
"""Return the time for havdalah, or None if not applicable.
If havdalah_offset is 0, uses the time for three_stars. Otherwise,
adds the offset to the time of sunset and uses that.
If it's currently a multi-day YomTov, and the end of the stretch is
after today... | python | def havdalah(self):
"""Return the time for havdalah, or None if not applicable.
If havdalah_offset is 0, uses the time for three_stars. Otherwise,
adds the offset to the time of sunset and uses that.
If it's currently a multi-day YomTov, and the end of the stretch is
after today... | [
"def",
"havdalah",
"(",
"self",
")",
":",
"today",
"=",
"HDate",
"(",
"gdate",
"=",
"self",
".",
"date",
",",
"diaspora",
"=",
"self",
".",
"location",
".",
"diaspora",
")",
"tomorrow",
"=",
"HDate",
"(",
"gdate",
"=",
"self",
".",
"date",
"+",
"dt... | Return the time for havdalah, or None if not applicable.
If havdalah_offset is 0, uses the time for three_stars. Otherwise,
adds the offset to the time of sunset and uses that.
If it's currently a multi-day YomTov, and the end of the stretch is
after today, the havdalah value is defined... | [
"Return",
"the",
"time",
"for",
"havdalah",
"or",
"None",
"if",
"not",
"applicable",
"."
] | train | https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/zmanim.py#L102-L123 |
royi1000/py-libhdate | hdate/zmanim.py | Zmanim.issur_melacha_in_effect | def issur_melacha_in_effect(self):
"""At the given time, return whether issur melacha is in effect."""
# TODO: Rewrite this in terms of candle_lighting/havdalah properties.
weekday = self.date.weekday()
tomorrow = self.date + dt.timedelta(days=1)
tomorrow_holiday_type = HDate(
... | python | def issur_melacha_in_effect(self):
"""At the given time, return whether issur melacha is in effect."""
# TODO: Rewrite this in terms of candle_lighting/havdalah properties.
weekday = self.date.weekday()
tomorrow = self.date + dt.timedelta(days=1)
tomorrow_holiday_type = HDate(
... | [
"def",
"issur_melacha_in_effect",
"(",
"self",
")",
":",
"# TODO: Rewrite this in terms of candle_lighting/havdalah properties.",
"weekday",
"=",
"self",
".",
"date",
".",
"weekday",
"(",
")",
"tomorrow",
"=",
"self",
".",
"date",
"+",
"dt",
".",
"timedelta",
"(",
... | At the given time, return whether issur melacha is in effect. | [
"At",
"the",
"given",
"time",
"return",
"whether",
"issur",
"melacha",
"is",
"in",
"effect",
"."
] | train | https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/zmanim.py#L126-L143 |
royi1000/py-libhdate | hdate/zmanim.py | Zmanim.gday_of_year | def gday_of_year(self):
"""Return the number of days since January 1 of the given year."""
return (self.date - dt.date(self.date.year, 1, 1)).days | python | def gday_of_year(self):
"""Return the number of days since January 1 of the given year."""
return (self.date - dt.date(self.date.year, 1, 1)).days | [
"def",
"gday_of_year",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"date",
"-",
"dt",
".",
"date",
"(",
"self",
".",
"date",
".",
"year",
",",
"1",
",",
"1",
")",
")",
".",
"days"
] | Return the number of days since January 1 of the given year. | [
"Return",
"the",
"number",
"of",
"days",
"since",
"January",
"1",
"of",
"the",
"given",
"year",
"."
] | train | https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/zmanim.py#L145-L147 |
royi1000/py-libhdate | hdate/zmanim.py | Zmanim.utc_minute_timezone | def utc_minute_timezone(self, minutes_from_utc):
"""Return the local time for a given time UTC."""
from_zone = tz.gettz('UTC')
to_zone = self.location.timezone
utc = dt.datetime.combine(self.date, dt.time()) + \
dt.timedelta(minutes=minutes_from_utc)
utc = utc.replace... | python | def utc_minute_timezone(self, minutes_from_utc):
"""Return the local time for a given time UTC."""
from_zone = tz.gettz('UTC')
to_zone = self.location.timezone
utc = dt.datetime.combine(self.date, dt.time()) + \
dt.timedelta(minutes=minutes_from_utc)
utc = utc.replace... | [
"def",
"utc_minute_timezone",
"(",
"self",
",",
"minutes_from_utc",
")",
":",
"from_zone",
"=",
"tz",
".",
"gettz",
"(",
"'UTC'",
")",
"to_zone",
"=",
"self",
".",
"location",
".",
"timezone",
"utc",
"=",
"dt",
".",
"datetime",
".",
"combine",
"(",
"self... | Return the local time for a given time UTC. | [
"Return",
"the",
"local",
"time",
"for",
"a",
"given",
"time",
"UTC",
"."
] | train | https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/zmanim.py#L149-L157 |
royi1000/py-libhdate | hdate/zmanim.py | Zmanim._get_utc_sun_time_deg | def _get_utc_sun_time_deg(self, deg):
"""
Return the times in minutes from 00:00 (utc) for a given sun altitude.
This is done for a given sun altitude in sunrise `deg` degrees
This function only works for altitudes sun really is.
If the sun never gets to this altitude, the retur... | python | def _get_utc_sun_time_deg(self, deg):
"""
Return the times in minutes from 00:00 (utc) for a given sun altitude.
This is done for a given sun altitude in sunrise `deg` degrees
This function only works for altitudes sun really is.
If the sun never gets to this altitude, the retur... | [
"def",
"_get_utc_sun_time_deg",
"(",
"self",
",",
"deg",
")",
":",
"gama",
"=",
"0",
"# location of sun in yearly cycle in radians",
"eqtime",
"=",
"0",
"# difference betwen sun noon and clock noon",
"decl",
"=",
"0",
"# sun declanation",
"hour_angle",
"=",
"0",
"# sola... | Return the times in minutes from 00:00 (utc) for a given sun altitude.
This is done for a given sun altitude in sunrise `deg` degrees
This function only works for altitudes sun really is.
If the sun never gets to this altitude, the returned sunset and sunrise
values will be negative. Th... | [
"Return",
"the",
"times",
"in",
"minutes",
"from",
"00",
":",
"00",
"(",
"utc",
")",
"for",
"a",
"given",
"sun",
"altitude",
"."
] | train | https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/zmanim.py#L159-L221 |
royi1000/py-libhdate | hdate/zmanim.py | Zmanim.get_utc_sun_time_full | def get_utc_sun_time_full(self):
"""Return a list of Jewish times for the given location."""
# sunset and rise time
sunrise, sunset = self._get_utc_sun_time_deg(90.833)
# shaa zmanit by gara, 1/12 of light time
sun_hour = (sunset - sunrise) // 12
midday = (sunset + sunri... | python | def get_utc_sun_time_full(self):
"""Return a list of Jewish times for the given location."""
# sunset and rise time
sunrise, sunset = self._get_utc_sun_time_deg(90.833)
# shaa zmanit by gara, 1/12 of light time
sun_hour = (sunset - sunrise) // 12
midday = (sunset + sunri... | [
"def",
"get_utc_sun_time_full",
"(",
"self",
")",
":",
"# sunset and rise time",
"sunrise",
",",
"sunset",
"=",
"self",
".",
"_get_utc_sun_time_deg",
"(",
"90.833",
")",
"# shaa zmanit by gara, 1/12 of light time",
"sun_hour",
"=",
"(",
"sunset",
"-",
"sunrise",
")",
... | Return a list of Jewish times for the given location. | [
"Return",
"a",
"list",
"of",
"Jewish",
"times",
"for",
"the",
"given",
"location",
"."
] | train | https://github.com/royi1000/py-libhdate/blob/12af759fb69f1d6403abed3762beaf5ace16a34b/hdate/zmanim.py#L223-L251 |
clee704/mutagenwrapper | mutagenwrapper/__init__.py | cutoff | def cutoff(s, length=120):
"""Cuts a given string if it is longer than a given length."""
if length < 5:
raise ValueError('length must be >= 5')
if len(s) <= length:
return s
else:
i = (length - 2) / 2
j = (length - 3) / 2
return s[:i] + '...' + s[-j:] | python | def cutoff(s, length=120):
"""Cuts a given string if it is longer than a given length."""
if length < 5:
raise ValueError('length must be >= 5')
if len(s) <= length:
return s
else:
i = (length - 2) / 2
j = (length - 3) / 2
return s[:i] + '...' + s[-j:] | [
"def",
"cutoff",
"(",
"s",
",",
"length",
"=",
"120",
")",
":",
"if",
"length",
"<",
"5",
":",
"raise",
"ValueError",
"(",
"'length must be >= 5'",
")",
"if",
"len",
"(",
"s",
")",
"<=",
"length",
":",
"return",
"s",
"else",
":",
"i",
"=",
"(",
"... | Cuts a given string if it is longer than a given length. | [
"Cuts",
"a",
"given",
"string",
"if",
"it",
"is",
"longer",
"than",
"a",
"given",
"length",
"."
] | train | https://github.com/clee704/mutagenwrapper/blob/f66ea03f0ee60c3718cc45236a46fdfb67f1c6ae/mutagenwrapper/__init__.py#L117-L126 |
clee704/mutagenwrapper | mutagenwrapper/__init__.py | MediaFile.save | def save(self, reload=False):
"""Save changes to the file."""
self.wrapper.raw.save()
if reload:
self.reload() | python | def save(self, reload=False):
"""Save changes to the file."""
self.wrapper.raw.save()
if reload:
self.reload() | [
"def",
"save",
"(",
"self",
",",
"reload",
"=",
"False",
")",
":",
"self",
".",
"wrapper",
".",
"raw",
".",
"save",
"(",
")",
"if",
"reload",
":",
"self",
".",
"reload",
"(",
")"
] | Save changes to the file. | [
"Save",
"changes",
"to",
"the",
"file",
"."
] | train | https://github.com/clee704/mutagenwrapper/blob/f66ea03f0ee60c3718cc45236a46fdfb67f1c6ae/mutagenwrapper/__init__.py#L61-L65 |
clee704/mutagenwrapper | mutagenwrapper/__init__.py | MediaFile.pprint | def pprint(self, raw=False):
"""Print the metadata in a human-friendly form.
if *raw* is *True*, print the unmodified keys and values.
"""
tags = self.wrapper if not raw else self.wrapper.raw
print u'{}:'.format(self.path)
names = tags.keys()
names.sort()
... | python | def pprint(self, raw=False):
"""Print the metadata in a human-friendly form.
if *raw* is *True*, print the unmodified keys and values.
"""
tags = self.wrapper if not raw else self.wrapper.raw
print u'{}:'.format(self.path)
names = tags.keys()
names.sort()
... | [
"def",
"pprint",
"(",
"self",
",",
"raw",
"=",
"False",
")",
":",
"tags",
"=",
"self",
".",
"wrapper",
"if",
"not",
"raw",
"else",
"self",
".",
"wrapper",
".",
"raw",
"print",
"u'{}:'",
".",
"format",
"(",
"self",
".",
"path",
")",
"names",
"=",
... | Print the metadata in a human-friendly form.
if *raw* is *True*, print the unmodified keys and values. | [
"Print",
"the",
"metadata",
"in",
"a",
"human",
"-",
"friendly",
"form",
".",
"if",
"*",
"raw",
"*",
"is",
"*",
"True",
"*",
"print",
"the",
"unmodified",
"keys",
"and",
"values",
"."
] | train | https://github.com/clee704/mutagenwrapper/blob/f66ea03f0ee60c3718cc45236a46fdfb67f1c6ae/mutagenwrapper/__init__.py#L71-L87 |
Fantomas42/mots-vides | mots_vides/stop_words.py | StopWord.rebase | def rebase(self, text, char='X'):
"""
Rebases text with stop words removed.
"""
regexp = re.compile(r'\b(%s)\b' % '|'.join(self.collection),
re.IGNORECASE | re.UNICODE)
def replace(m):
word = m.group(1)
return char * len(word)
... | python | def rebase(self, text, char='X'):
"""
Rebases text with stop words removed.
"""
regexp = re.compile(r'\b(%s)\b' % '|'.join(self.collection),
re.IGNORECASE | re.UNICODE)
def replace(m):
word = m.group(1)
return char * len(word)
... | [
"def",
"rebase",
"(",
"self",
",",
"text",
",",
"char",
"=",
"'X'",
")",
":",
"regexp",
"=",
"re",
".",
"compile",
"(",
"r'\\b(%s)\\b'",
"%",
"'|'",
".",
"join",
"(",
"self",
".",
"collection",
")",
",",
"re",
".",
"IGNORECASE",
"|",
"re",
".",
"... | Rebases text with stop words removed. | [
"Rebases",
"text",
"with",
"stop",
"words",
"removed",
"."
] | train | https://github.com/Fantomas42/mots-vides/blob/eaeccf73bdb415d0c5559ccd74de360b37a2bbac/mots_vides/stop_words.py#L75-L86 |
cimatosa/progression | progression/progress.py | _loop_wrapper_func | def _loop_wrapper_func(func, args, shared_mem_run, shared_mem_pause, interval, sigint, sigterm, name,
logging_level, conn_send, func_running, log_queue):
"""
to be executed as a separate process (that's why this functions is declared static)
"""
prefix = get_identifier(name) +... | python | def _loop_wrapper_func(func, args, shared_mem_run, shared_mem_pause, interval, sigint, sigterm, name,
logging_level, conn_send, func_running, log_queue):
"""
to be executed as a separate process (that's why this functions is declared static)
"""
prefix = get_identifier(name) +... | [
"def",
"_loop_wrapper_func",
"(",
"func",
",",
"args",
",",
"shared_mem_run",
",",
"shared_mem_pause",
",",
"interval",
",",
"sigint",
",",
"sigterm",
",",
"name",
",",
"logging_level",
",",
"conn_send",
",",
"func_running",
",",
"log_queue",
")",
":",
"prefix... | to be executed as a separate process (that's why this functions is declared static) | [
"to",
"be",
"executed",
"as",
"a",
"separate",
"process",
"(",
"that",
"s",
"why",
"this",
"functions",
"is",
"declared",
"static",
")"
] | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L263-L323 |
cimatosa/progression | progression/progress.py | show_stat_base | def show_stat_base(count_value, max_count_value, prepend, speed, tet, ttg, width, **kwargs):
"""A function that formats the progress information
This function will be called periodically for each progress that is monitored.
Overwrite this function in a subclass to implement a specific formating of the prog... | python | def show_stat_base(count_value, max_count_value, prepend, speed, tet, ttg, width, **kwargs):
"""A function that formats the progress information
This function will be called periodically for each progress that is monitored.
Overwrite this function in a subclass to implement a specific formating of the prog... | [
"def",
"show_stat_base",
"(",
"count_value",
",",
"max_count_value",
",",
"prepend",
",",
"speed",
",",
"tet",
",",
"ttg",
",",
"width",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError"
] | A function that formats the progress information
This function will be called periodically for each progress that is monitored.
Overwrite this function in a subclass to implement a specific formating of the progress information
:param count_value: a number holding the current state
:param max_cou... | [
"A",
"function",
"that",
"formats",
"the",
"progress",
"information"
] | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L574-L590 |
cimatosa/progression | progression/progress.py | _show_stat_wrapper_Progress | def _show_stat_wrapper_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, add_args,
i, lock):
"""
calculate
"""
count_value, max_count_value, speed, tet, ttg, = Pro... | python | def _show_stat_wrapper_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, add_args,
i, lock):
"""
calculate
"""
count_value, max_count_value, speed, tet, ttg, = Pro... | [
"def",
"_show_stat_wrapper_Progress",
"(",
"count",
",",
"last_count",
",",
"start_time",
",",
"max_count",
",",
"speed_calc_cycles",
",",
"width",
",",
"q",
",",
"last_speed",
",",
"prepend",
",",
"show_stat_function",
",",
"add_args",
",",
"i",
",",
"lock",
... | calculate | [
"calculate"
] | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L592-L606 |
cimatosa/progression | progression/progress.py | _show_stat_wrapper_multi_Progress | def _show_stat_wrapper_multi_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, len_,
add_args, lock, info_line, no_move_up=False):
"""
call the static method s... | python | def _show_stat_wrapper_multi_Progress(count, last_count, start_time, max_count, speed_calc_cycles,
width, q, last_speed, prepend, show_stat_function, len_,
add_args, lock, info_line, no_move_up=False):
"""
call the static method s... | [
"def",
"_show_stat_wrapper_multi_Progress",
"(",
"count",
",",
"last_count",
",",
"start_time",
",",
"max_count",
",",
"speed_calc_cycles",
",",
"width",
",",
"q",
",",
"last_speed",
",",
"prepend",
",",
"show_stat_function",
",",
"len_",
",",
"add_args",
",",
"... | call the static method show_stat_wrapper for each process | [
"call",
"the",
"static",
"method",
"show_stat_wrapper",
"for",
"each",
"process"
] | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L608-L638 |
cimatosa/progression | progression/progress.py | getCountKwargs | def getCountKwargs(func):
""" Returns a list ["count kwarg", "count_max kwarg"] for a
given function. Valid combinations are defined in
`progress.validCountKwargs`.
Returns None if no keyword arguments are found.
"""
# Get all arguments of the function
if hasattr(func, "__code__"):
... | python | def getCountKwargs(func):
""" Returns a list ["count kwarg", "count_max kwarg"] for a
given function. Valid combinations are defined in
`progress.validCountKwargs`.
Returns None if no keyword arguments are found.
"""
# Get all arguments of the function
if hasattr(func, "__code__"):
... | [
"def",
"getCountKwargs",
"(",
"func",
")",
":",
"# Get all arguments of the function",
"if",
"hasattr",
"(",
"func",
",",
"\"__code__\"",
")",
":",
"func_args",
"=",
"func",
".",
"__code__",
".",
"co_varnames",
"[",
":",
"func",
".",
"__code__",
".",
"co_argco... | Returns a list ["count kwarg", "count_max kwarg"] for a
given function. Valid combinations are defined in
`progress.validCountKwargs`.
Returns None if no keyword arguments are found. | [
"Returns",
"a",
"list",
"[",
"count",
"kwarg",
"count_max",
"kwarg",
"]",
"for",
"a",
"given",
"function",
".",
"Valid",
"combinations",
"are",
"defined",
"in",
"progress",
".",
"validCountKwargs",
".",
"Returns",
"None",
"if",
"no",
"keyword",
"arguments",
... | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L1378-L1392 |
cimatosa/progression | progression/progress.py | humanize_speed | def humanize_speed(c_per_sec):
"""convert a speed in counts per second to counts per [s, min, h, d], choosing the smallest value greater zero.
"""
scales = [60, 60, 24]
units = ['c/s', 'c/min', 'c/h', 'c/d']
speed = c_per_sec
i = 0
if speed > 0:
while (speed < 1) and (i < len(scales)... | python | def humanize_speed(c_per_sec):
"""convert a speed in counts per second to counts per [s, min, h, d], choosing the smallest value greater zero.
"""
scales = [60, 60, 24]
units = ['c/s', 'c/min', 'c/h', 'c/d']
speed = c_per_sec
i = 0
if speed > 0:
while (speed < 1) and (i < len(scales)... | [
"def",
"humanize_speed",
"(",
"c_per_sec",
")",
":",
"scales",
"=",
"[",
"60",
",",
"60",
",",
"24",
"]",
"units",
"=",
"[",
"'c/s'",
",",
"'c/min'",
",",
"'c/h'",
",",
"'c/d'",
"]",
"speed",
"=",
"c_per_sec",
"i",
"=",
"0",
"if",
"speed",
">",
"... | convert a speed in counts per second to counts per [s, min, h, d], choosing the smallest value greater zero. | [
"convert",
"a",
"speed",
"in",
"counts",
"per",
"second",
"to",
"counts",
"per",
"[",
"s",
"min",
"h",
"d",
"]",
"choosing",
"the",
"smallest",
"value",
"greater",
"zero",
"."
] | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L1394-L1406 |
cimatosa/progression | progression/progress.py | humanize_time | def humanize_time(secs):
"""convert second in to hh:mm:ss format
"""
if secs is None:
return '--'
if secs < 1:
return "{:.2f}ms".format(secs*1000)
elif secs < 10:
return "{:.2f}s".format(secs)
else:
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins,... | python | def humanize_time(secs):
"""convert second in to hh:mm:ss format
"""
if secs is None:
return '--'
if secs < 1:
return "{:.2f}ms".format(secs*1000)
elif secs < 10:
return "{:.2f}s".format(secs)
else:
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins,... | [
"def",
"humanize_time",
"(",
"secs",
")",
":",
"if",
"secs",
"is",
"None",
":",
"return",
"'--'",
"if",
"secs",
"<",
"1",
":",
"return",
"\"{:.2f}ms\"",
".",
"format",
"(",
"secs",
"*",
"1000",
")",
"elif",
"secs",
"<",
"10",
":",
"return",
"\"{:.2f}... | convert second in to hh:mm:ss format | [
"convert",
"second",
"in",
"to",
"hh",
":",
"mm",
":",
"ss",
"format"
] | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L1409-L1422 |
cimatosa/progression | progression/progress.py | Loop.__cleanup | def __cleanup(self):
"""
Wait at most twice as long as the given repetition interval
for the _wrapper_function to terminate.
If after that time the _wrapper_function has not terminated,
send SIGTERM to and the process.
Wait at most five times as long as ... | python | def __cleanup(self):
"""
Wait at most twice as long as the given repetition interval
for the _wrapper_function to terminate.
If after that time the _wrapper_function has not terminated,
send SIGTERM to and the process.
Wait at most five times as long as ... | [
"def",
"__cleanup",
"(",
"self",
")",
":",
"# set run to False and wait some time -> see what happens ",
"self",
".",
"_run",
".",
"value",
"=",
"False",
"if",
"check_process_termination",
"(",
"proc",
"=",
"self",
".",
"_proc",
",",
"timeout",
"=",
"2",
... | Wait at most twice as long as the given repetition interval
for the _wrapper_function to terminate.
If after that time the _wrapper_function has not terminated,
send SIGTERM to and the process.
Wait at most five times as long as the given repetition interval
for... | [
"Wait",
"at",
"most",
"twice",
"as",
"long",
"as",
"the",
"given",
"repetition",
"interval",
"for",
"the",
"_wrapper_function",
"to",
"terminate",
".",
"If",
"after",
"that",
"time",
"the",
"_wrapper_function",
"has",
"not",
"terminated",
"send",
"SIGTERM",
"t... | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L422-L454 |
cimatosa/progression | progression/progress.py | Loop.start | def start(self, timeout=None):
"""
uses multiprocess Process to call _wrapper_func in subprocess
"""
if self.is_alive():
log.warning("a process with pid %s is already running", self._proc.pid)
return
self._run.value = True
self._func... | python | def start(self, timeout=None):
"""
uses multiprocess Process to call _wrapper_func in subprocess
"""
if self.is_alive():
log.warning("a process with pid %s is already running", self._proc.pid)
return
self._run.value = True
self._func... | [
"def",
"start",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"is_alive",
"(",
")",
":",
"log",
".",
"warning",
"(",
"\"a process with pid %s is already running\"",
",",
"self",
".",
"_proc",
".",
"pid",
")",
"return",
"self",
".... | uses multiprocess Process to call _wrapper_func in subprocess | [
"uses",
"multiprocess",
"Process",
"to",
"call",
"_wrapper_func",
"in",
"subprocess"
] | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L465-L516 |
cimatosa/progression | progression/progress.py | Loop.stop | def stop(self):
"""
stops the process triggered by start
Setting the shared memory boolean run to false, which should prevent
the loop from repeating. Call __cleanup to make sure the process
stopped. After that we could trigger start() again.
"""
... | python | def stop(self):
"""
stops the process triggered by start
Setting the shared memory boolean run to false, which should prevent
the loop from repeating. Call __cleanup to make sure the process
stopped. After that we could trigger start() again.
"""
... | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"_proc",
".",
"terminate",
"(",
")",
"if",
"self",
".",
"_proc",
"is",
"not",
"None",
":",
"self",
".",
"__cleanup",
"(",
")",
"if",
"self",
".",
"... | stops the process triggered by start
Setting the shared memory boolean run to false, which should prevent
the loop from repeating. Call __cleanup to make sure the process
stopped. After that we could trigger start() again. | [
"stops",
"the",
"process",
"triggered",
"by",
"start",
"Setting",
"the",
"shared",
"memory",
"boolean",
"run",
"to",
"false",
"which",
"should",
"prevent",
"the",
"loop",
"from",
"repeating",
".",
"Call",
"__cleanup",
"to",
"make",
"sure",
"the",
"process",
... | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L518-L537 |
cimatosa/progression | progression/progress.py | Progress._calc | def _calc(count,
last_count,
start_time,
max_count,
speed_calc_cycles,
q,
last_speed,
lock):
"""do the pre calculations in order to get TET, speed, TTG
:param count: count
... | python | def _calc(count,
last_count,
start_time,
max_count,
speed_calc_cycles,
q,
last_speed,
lock):
"""do the pre calculations in order to get TET, speed, TTG
:param count: count
... | [
"def",
"_calc",
"(",
"count",
",",
"last_count",
",",
"start_time",
",",
"max_count",
",",
"speed_calc_cycles",
",",
"q",
",",
"last_speed",
",",
"lock",
")",
":",
"count_value",
"=",
"count",
".",
"value",
"start_time_value",
"=",
"start_time",
".",
"value"... | do the pre calculations in order to get TET, speed, TTG
:param count: count
:param last_count: count at the last call, allows to treat the case of no progress
between sequential calls
:param start_time: the time when start was triggered
... | [
"do",
"the",
"pre",
"calculations",
"in",
"order",
"to",
"get",
"TET",
"speed",
"TTG",
":",
"param",
"count",
":",
"count",
":",
"param",
"last_count",
":",
"count",
"at",
"the",
"last",
"call",
"allows",
"to",
"treat",
"the",
"case",
"of",
"no",
"prog... | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L806-L874 |
cimatosa/progression | progression/progress.py | Progress._reset_i | def _reset_i(self, i):
"""
reset i-th progress information
"""
self.count[i].value=0
log.debug("reset counter %s", i)
self.lock[i].acquire()
for x in range(self.q[i].qsize()):
self.q[i].get()
self.lock[i].release()
self.sta... | python | def _reset_i(self, i):
"""
reset i-th progress information
"""
self.count[i].value=0
log.debug("reset counter %s", i)
self.lock[i].acquire()
for x in range(self.q[i].qsize()):
self.q[i].get()
self.lock[i].release()
self.sta... | [
"def",
"_reset_i",
"(",
"self",
",",
"i",
")",
":",
"self",
".",
"count",
"[",
"i",
"]",
".",
"value",
"=",
"0",
"log",
".",
"debug",
"(",
"\"reset counter %s\"",
",",
"i",
")",
"self",
".",
"lock",
"[",
"i",
"]",
".",
"acquire",
"(",
")",
"for... | reset i-th progress information | [
"reset",
"i",
"-",
"th",
"progress",
"information"
] | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L883-L894 |
cimatosa/progression | progression/progress.py | Progress._show_stat | def _show_stat(self):
"""
convenient functions to call the static show_stat_wrapper_multi with
the given class members
"""
_show_stat_wrapper_multi_Progress(self.count,
self.last_count,
s... | python | def _show_stat(self):
"""
convenient functions to call the static show_stat_wrapper_multi with
the given class members
"""
_show_stat_wrapper_multi_Progress(self.count,
self.last_count,
s... | [
"def",
"_show_stat",
"(",
"self",
")",
":",
"_show_stat_wrapper_multi_Progress",
"(",
"self",
".",
"count",
",",
"self",
".",
"last_count",
",",
"self",
".",
"start_time",
",",
"self",
".",
"max_count",
",",
"self",
".",
"speed_calc_cycles",
",",
"self",
"."... | convenient functions to call the static show_stat_wrapper_multi with
the given class members | [
"convenient",
"functions",
"to",
"call",
"the",
"static",
"show_stat_wrapper_multi",
"with",
"the",
"given",
"class",
"members"
] | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L896-L915 |
cimatosa/progression | progression/progress.py | Progress.start | def start(self):
"""
start
"""
# before printing any output to stout, we can now check this
# variable to see if any other ProgressBar has reserved that
# terminal.
if (self.__class__.__name__ in terminal.TERMINAL_PRINT_LOOP_CLASSES):
if n... | python | def start(self):
"""
start
"""
# before printing any output to stout, we can now check this
# variable to see if any other ProgressBar has reserved that
# terminal.
if (self.__class__.__name__ in terminal.TERMINAL_PRINT_LOOP_CLASSES):
if n... | [
"def",
"start",
"(",
"self",
")",
":",
"# before printing any output to stout, we can now check this",
"# variable to see if any other ProgressBar has reserved that",
"# terminal.",
"if",
"(",
"self",
".",
"__class__",
".",
"__name__",
"in",
"terminal",
".",
"TERMINAL_PRINT_LOO... | start | [
"start"
] | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L931-L945 |
cimatosa/progression | progression/progress.py | Progress.stop | def stop(self):
"""
trigger clean up by hand, needs to be done when not using
context management via 'with' statement
- will terminate loop process
- show a last progress -> see the full 100% on exit
- releases terminal reservation
"""... | python | def stop(self):
"""
trigger clean up by hand, needs to be done when not using
context management via 'with' statement
- will terminate loop process
- show a last progress -> see the full 100% on exit
- releases terminal reservation
"""... | [
"def",
"stop",
"(",
"self",
")",
":",
"super",
"(",
"Progress",
",",
"self",
")",
".",
"stop",
"(",
")",
"terminal",
".",
"terminal_unreserve",
"(",
"progress_obj",
"=",
"self",
",",
"verbose",
"=",
"self",
".",
"verbose",
")",
"if",
"self",
".",
"sh... | trigger clean up by hand, needs to be done when not using
context management via 'with' statement
- will terminate loop process
- show a last progress -> see the full 100% on exit
- releases terminal reservation | [
"trigger",
"clean",
"up",
"by",
"hand",
"needs",
"to",
"be",
"done",
"when",
"not",
"using",
"context",
"management",
"via",
"with",
"statement",
"-",
"will",
"terminate",
"loop",
"process",
"-",
"show",
"a",
"last",
"progress",
"-",
">",
"see",
"the",
"... | train | https://github.com/cimatosa/progression/blob/82cf74a25a47f9bda96157cc2c88e5975c20b41d/progression/progress.py#L947-L970 |
aiidateam/aiida-nwchem | aiida_nwchem/parsers/basic.py | BasicParser._get_output_nodes | def _get_output_nodes(self, output_path, error_path):
"""
Extracts output nodes from the standard output and standard error
files.
"""
from aiida.orm.data.array.trajectory import TrajectoryData
import re
state = None
step = None
scale = None
... | python | def _get_output_nodes(self, output_path, error_path):
"""
Extracts output nodes from the standard output and standard error
files.
"""
from aiida.orm.data.array.trajectory import TrajectoryData
import re
state = None
step = None
scale = None
... | [
"def",
"_get_output_nodes",
"(",
"self",
",",
"output_path",
",",
"error_path",
")",
":",
"from",
"aiida",
".",
"orm",
".",
"data",
".",
"array",
".",
"trajectory",
"import",
"TrajectoryData",
"import",
"re",
"state",
"=",
"None",
"step",
"=",
"None",
"sca... | Extracts output nodes from the standard output and standard error
files. | [
"Extracts",
"output",
"nodes",
"from",
"the",
"standard",
"output",
"and",
"standard",
"error",
"files",
"."
] | train | https://github.com/aiidateam/aiida-nwchem/blob/21034e7f8ea8249948065c28030f4b572a6ecf05/aiida_nwchem/parsers/basic.py#L32-L78 |
sveetch/boussole | boussole/resolver.py | ImportPathsResolver.candidate_paths | def candidate_paths(self, filepath):
"""
Return candidates path for given path
* If Filename does not starts with ``_``, will build a candidate for
both with and without ``_`` prefix;
* Will build For each available extensions if filename does not have
an explicit ex... | python | def candidate_paths(self, filepath):
"""
Return candidates path for given path
* If Filename does not starts with ``_``, will build a candidate for
both with and without ``_`` prefix;
* Will build For each available extensions if filename does not have
an explicit ex... | [
"def",
"candidate_paths",
"(",
"self",
",",
"filepath",
")",
":",
"filelead",
",",
"filetail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filepath",
")",
"name",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filetail",
")",
"# Remov... | Return candidates path for given path
* If Filename does not starts with ``_``, will build a candidate for
both with and without ``_`` prefix;
* Will build For each available extensions if filename does not have
an explicit extension;
* Leading path directory is preserved;
... | [
"Return",
"candidates",
"path",
"for",
"given",
"path"
] | train | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/resolver.py#L37-L79 |
sveetch/boussole | boussole/resolver.py | ImportPathsResolver.check_candidate_exists | def check_candidate_exists(self, basepath, candidates):
"""
Check that at least one candidate exist into a directory.
Args:
basepath (str): Directory path where to search for candidate.
candidates (list): List of candidate file paths.
Returns:
list: ... | python | def check_candidate_exists(self, basepath, candidates):
"""
Check that at least one candidate exist into a directory.
Args:
basepath (str): Directory path where to search for candidate.
candidates (list): List of candidate file paths.
Returns:
list: ... | [
"def",
"check_candidate_exists",
"(",
"self",
",",
"basepath",
",",
"candidates",
")",
":",
"checked",
"=",
"[",
"]",
"for",
"item",
"in",
"candidates",
":",
"abspath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"basepath",
",",
"item",
")",
"if",
"os",... | Check that at least one candidate exist into a directory.
Args:
basepath (str): Directory path where to search for candidate.
candidates (list): List of candidate file paths.
Returns:
list: List of existing candidates. | [
"Check",
"that",
"at",
"least",
"one",
"candidate",
"exist",
"into",
"a",
"directory",
"."
] | train | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/resolver.py#L81-L98 |
sveetch/boussole | boussole/resolver.py | ImportPathsResolver.resolve | def resolve(self, sourcepath, paths, library_paths=None):
"""
Resolve given paths from given base paths
Return resolved path list.
Note:
Resolving strategy is made like libsass do, meaning paths in
import rules are resolved from the source file where the import
... | python | def resolve(self, sourcepath, paths, library_paths=None):
"""
Resolve given paths from given base paths
Return resolved path list.
Note:
Resolving strategy is made like libsass do, meaning paths in
import rules are resolved from the source file where the import
... | [
"def",
"resolve",
"(",
"self",
",",
"sourcepath",
",",
"paths",
",",
"library_paths",
"=",
"None",
")",
":",
"# Split basedir/filename from sourcepath, so the first resolving",
"# basepath is the sourcepath directory, then the optionnal",
"# given libraries",
"basedir",
",",
"f... | Resolve given paths from given base paths
Return resolved path list.
Note:
Resolving strategy is made like libsass do, meaning paths in
import rules are resolved from the source file where the import
rules have been finded.
If import rule is not explici... | [
"Resolve",
"given",
"paths",
"from",
"given",
"base",
"paths"
] | train | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/resolver.py#L100-L183 |
sveetch/boussole | boussole/conf/yaml_backend.py | SettingsBackendYaml.dump | def dump(self, content, filepath, indent=4):
"""
Dump settings content to filepath.
Args:
content (str): Settings content.
filepath (str): Settings file location.
"""
with open(filepath, 'w') as fp:
pyaml.dump(content, dst=fp, indent=indent) | python | def dump(self, content, filepath, indent=4):
"""
Dump settings content to filepath.
Args:
content (str): Settings content.
filepath (str): Settings file location.
"""
with open(filepath, 'w') as fp:
pyaml.dump(content, dst=fp, indent=indent) | [
"def",
"dump",
"(",
"self",
",",
"content",
",",
"filepath",
",",
"indent",
"=",
"4",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"'w'",
")",
"as",
"fp",
":",
"pyaml",
".",
"dump",
"(",
"content",
",",
"dst",
"=",
"fp",
",",
"indent",
"=",
... | Dump settings content to filepath.
Args:
content (str): Settings content.
filepath (str): Settings file location. | [
"Dump",
"settings",
"content",
"to",
"filepath",
"."
] | train | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/yaml_backend.py#L31-L40 |
sveetch/boussole | boussole/conf/yaml_backend.py | SettingsBackendYaml.parse | def parse(self, filepath, content):
"""
Parse opened settings content using YAML parser.
Args:
filepath (str): Settings object, depends from backend
content (str): Settings content from opened file, depends from
backend.
Raises:
bouss... | python | def parse(self, filepath, content):
"""
Parse opened settings content using YAML parser.
Args:
filepath (str): Settings object, depends from backend
content (str): Settings content from opened file, depends from
backend.
Raises:
bouss... | [
"def",
"parse",
"(",
"self",
",",
"filepath",
",",
"content",
")",
":",
"try",
":",
"parsed",
"=",
"yaml",
".",
"load",
"(",
"content",
")",
"except",
"yaml",
".",
"YAMLError",
"as",
"exc",
":",
"msg",
"=",
"\"No YAML object could be decoded from file: {}\\n... | Parse opened settings content using YAML parser.
Args:
filepath (str): Settings object, depends from backend
content (str): Settings content from opened file, depends from
backend.
Raises:
boussole.exceptions.SettingsBackendError: If parser can not d... | [
"Parse",
"opened",
"settings",
"content",
"using",
"YAML",
"parser",
"."
] | train | https://github.com/sveetch/boussole/blob/22cc644e9d633f41ebfc167d427a71c1726cee21/boussole/conf/yaml_backend.py#L42-L64 |
tr3buchet/twiceredis | twiceredis/client.py | DisconnectingSentinel.filter_slaves | def filter_slaves(selfie, slaves):
"""
Remove slaves that are in an ODOWN or SDOWN state
also remove slaves that do not have 'ok' master-link-status
"""
return [(s['ip'], s['port']) for s in slaves
if not s['is_odown'] and
not s['is_sdown'] and
... | python | def filter_slaves(selfie, slaves):
"""
Remove slaves that are in an ODOWN or SDOWN state
also remove slaves that do not have 'ok' master-link-status
"""
return [(s['ip'], s['port']) for s in slaves
if not s['is_odown'] and
not s['is_sdown'] and
... | [
"def",
"filter_slaves",
"(",
"selfie",
",",
"slaves",
")",
":",
"return",
"[",
"(",
"s",
"[",
"'ip'",
"]",
",",
"s",
"[",
"'port'",
"]",
")",
"for",
"s",
"in",
"slaves",
"if",
"not",
"s",
"[",
"'is_odown'",
"]",
"and",
"not",
"s",
"[",
"'is_sdown... | Remove slaves that are in an ODOWN or SDOWN state
also remove slaves that do not have 'ok' master-link-status | [
"Remove",
"slaves",
"that",
"are",
"in",
"an",
"ODOWN",
"or",
"SDOWN",
"state",
"also",
"remove",
"slaves",
"that",
"do",
"not",
"have",
"ok",
"master",
"-",
"link",
"-",
"status"
] | train | https://github.com/tr3buchet/twiceredis/blob/c7baa4d66087092b40f7ebd9139e3b9bb7087707/twiceredis/client.py#L50-L58 |
tr3buchet/twiceredis | twiceredis/client.py | Listener.get_message | def get_message(zelf):
"""
get one message if available else return None
if message is available returns the result of handler(message)
does not block!
if you would like to call your handler manually, this is the way to
go. don't pass in a handler to Listener() and the d... | python | def get_message(zelf):
"""
get one message if available else return None
if message is available returns the result of handler(message)
does not block!
if you would like to call your handler manually, this is the way to
go. don't pass in a handler to Listener() and the d... | [
"def",
"get_message",
"(",
"zelf",
")",
":",
"try",
":",
"message",
"=",
"zelf",
".",
"r",
".",
"master",
".",
"rpoplpush",
"(",
"zelf",
".",
"lijst",
",",
"zelf",
".",
"_processing",
")",
"if",
"message",
":",
"# NOTE(tr3buchet): got a message, process it",... | get one message if available else return None
if message is available returns the result of handler(message)
does not block!
if you would like to call your handler manually, this is the way to
go. don't pass in a handler to Listener() and the default handler will
log and return ... | [
"get",
"one",
"message",
"if",
"available",
"else",
"return",
"None",
"if",
"message",
"is",
"available",
"returns",
"the",
"result",
"of",
"handler",
"(",
"message",
")",
"does",
"not",
"block!"
] | train | https://github.com/tr3buchet/twiceredis/blob/c7baa4d66087092b40f7ebd9139e3b9bb7087707/twiceredis/client.py#L144-L161 |
tr3buchet/twiceredis | twiceredis/client.py | Listener.listen | def listen(zelf):
"""
listen indefinitely, handling messages as they come
all redis specific exceptions are handled, anything your handler raises
will not be handled. setting active to False on the Listener object
will gracefully stop the listen() function
"""
wh... | python | def listen(zelf):
"""
listen indefinitely, handling messages as they come
all redis specific exceptions are handled, anything your handler raises
will not be handled. setting active to False on the Listener object
will gracefully stop the listen() function
"""
wh... | [
"def",
"listen",
"(",
"zelf",
")",
":",
"while",
"zelf",
".",
"active",
":",
"try",
":",
"msg",
"=",
"zelf",
".",
"r",
".",
"master",
".",
"brpoplpush",
"(",
"zelf",
".",
"lijst",
",",
"zelf",
".",
"_processing",
",",
"zelf",
".",
"read_time",
")",... | listen indefinitely, handling messages as they come
all redis specific exceptions are handled, anything your handler raises
will not be handled. setting active to False on the Listener object
will gracefully stop the listen() function | [
"listen",
"indefinitely",
"handling",
"messages",
"as",
"they",
"come"
] | train | https://github.com/tr3buchet/twiceredis/blob/c7baa4d66087092b40f7ebd9139e3b9bb7087707/twiceredis/client.py#L163-L182 |
ionelmc/python-cogen | cogen/core/coroutines.py | CoroutineInstance.run_op | def run_op(self, op, sched):
"""
Handle the operation:
* if coro is in STATE_RUNNING, send or throw the given op
* if coro is in STATE_NEED_INIT, call the init function and if it
doesn't return a generator, set STATE_COMPLETED and set the result
to whatever t... | python | def run_op(self, op, sched):
"""
Handle the operation:
* if coro is in STATE_RUNNING, send or throw the given op
* if coro is in STATE_NEED_INIT, call the init function and if it
doesn't return a generator, set STATE_COMPLETED and set the result
to whatever t... | [
"def",
"run_op",
"(",
"self",
",",
"op",
",",
"sched",
")",
":",
"if",
"op",
"is",
"self",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"Running coro %s with itself. Something is fishy.\"",
"%",
"op",
")",
"assert",
"self",
".",
"state",
"<",
... | Handle the operation:
* if coro is in STATE_RUNNING, send or throw the given op
* if coro is in STATE_NEED_INIT, call the init function and if it
doesn't return a generator, set STATE_COMPLETED and set the result
to whatever the function returned.
* if StopIterati... | [
"Handle",
"the",
"operation",
":",
"*",
"if",
"coro",
"is",
"in",
"STATE_RUNNING",
"send",
"or",
"throw",
"the",
"given",
"op",
"*",
"if",
"coro",
"is",
"in",
"STATE_NEED_INIT",
"call",
"the",
"init",
"function",
"and",
"if",
"it",
"doesn",
"t",
"return"... | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/coroutines.py#L159-L255 |
yuanxu/django-bootstrap3-validator | bootstrap_validator/templatetags/bootstrap_validator.py | render_field | def render_field(field):
"""
渲染字段验证代码
:param field:
:type field: django.forms.Field
:return:
"""
field = field.field if isinstance(field, forms.BoundField) else field
validators = {}
def no_compare_validator():
return not ('lessThan' in validators or 'greaterThan' in valida... | python | def render_field(field):
"""
渲染字段验证代码
:param field:
:type field: django.forms.Field
:return:
"""
field = field.field if isinstance(field, forms.BoundField) else field
validators = {}
def no_compare_validator():
return not ('lessThan' in validators or 'greaterThan' in valida... | [
"def",
"render_field",
"(",
"field",
")",
":",
"field",
"=",
"field",
".",
"field",
"if",
"isinstance",
"(",
"field",
",",
"forms",
".",
"BoundField",
")",
"else",
"field",
"validators",
"=",
"{",
"}",
"def",
"no_compare_validator",
"(",
")",
":",
"retur... | 渲染字段验证代码
:param field:
:type field: django.forms.Field
:return: | [
"渲染字段验证代码",
":",
"param",
"field",
":",
":",
"type",
"field",
":",
"django",
".",
"forms",
".",
"Field",
":",
"return",
":"
] | train | https://github.com/yuanxu/django-bootstrap3-validator/blob/138865c79782875076c91de4252aaf2dd8567101/bootstrap_validator/templatetags/bootstrap_validator.py#L129-L187 |
moonso/vcftoolbox | vcftoolbox/get_header.py | get_vcf_header | def get_vcf_header(source):
"""Get the header lines of a vcf file
Args:
source(iterable): A vcf file
Returns:
head (HeaderParser): A headerparser object
"""
head = HeaderParser()
#Parse the header lines
for line in source:
line = line.rst... | python | def get_vcf_header(source):
"""Get the header lines of a vcf file
Args:
source(iterable): A vcf file
Returns:
head (HeaderParser): A headerparser object
"""
head = HeaderParser()
#Parse the header lines
for line in source:
line = line.rst... | [
"def",
"get_vcf_header",
"(",
"source",
")",
":",
"head",
"=",
"HeaderParser",
"(",
")",
"#Parse the header lines",
"for",
"line",
"in",
"source",
":",
"line",
"=",
"line",
".",
"rstrip",
"(",
")",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
... | Get the header lines of a vcf file
Args:
source(iterable): A vcf file
Returns:
head (HeaderParser): A headerparser object | [
"Get",
"the",
"header",
"lines",
"of",
"a",
"vcf",
"file",
"Args",
":",
"source",
"(",
"iterable",
")",
":",
"A",
"vcf",
"file",
"Returns",
":",
"head",
"(",
"HeaderParser",
")",
":",
"A",
"headerparser",
"object"
] | train | https://github.com/moonso/vcftoolbox/blob/438fb1d85a83812c389774b94802eb5921c89e3a/vcftoolbox/get_header.py#L8-L31 |
ionelmc/python-cogen | examples/cogen-irc/CogenIrcApp/cogenircapp/websetup.py | setup_config | def setup_config(command, filename, section, vars):
"""Place any commands to setup cogenircapp here"""
conf = appconfig('config:' + filename)
load_environment(conf.global_conf, conf.local_conf) | python | def setup_config(command, filename, section, vars):
"""Place any commands to setup cogenircapp here"""
conf = appconfig('config:' + filename)
load_environment(conf.global_conf, conf.local_conf) | [
"def",
"setup_config",
"(",
"command",
",",
"filename",
",",
"section",
",",
"vars",
")",
":",
"conf",
"=",
"appconfig",
"(",
"'config:'",
"+",
"filename",
")",
"load_environment",
"(",
"conf",
".",
"global_conf",
",",
"conf",
".",
"local_conf",
")"
] | Place any commands to setup cogenircapp here | [
"Place",
"any",
"commands",
"to",
"setup",
"cogenircapp",
"here"
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/cogen-irc/CogenIrcApp/cogenircapp/websetup.py#L11-L14 |
SetBased/py-etlt | etlt/condition/SimpleConditionFactory.py | SimpleConditionFactory._split_scheme | def _split_scheme(expression):
"""
Splits the scheme and actual expression
:param str expression: The expression.
:rtype: str
"""
match = re.search(r'^([a-z]+):(.*)$', expression)
if not match:
scheme = 'plain'
actual = expression
... | python | def _split_scheme(expression):
"""
Splits the scheme and actual expression
:param str expression: The expression.
:rtype: str
"""
match = re.search(r'^([a-z]+):(.*)$', expression)
if not match:
scheme = 'plain'
actual = expression
... | [
"def",
"_split_scheme",
"(",
"expression",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'^([a-z]+):(.*)$'",
",",
"expression",
")",
"if",
"not",
"match",
":",
"scheme",
"=",
"'plain'",
"actual",
"=",
"expression",
"else",
":",
"scheme",
"=",
"match"... | Splits the scheme and actual expression
:param str expression: The expression.
:rtype: str | [
"Splits",
"the",
"scheme",
"and",
"actual",
"expression"
] | train | https://github.com/SetBased/py-etlt/blob/1c5b8ea60293c14f54d7845a9fe5c595021f66f2/etlt/condition/SimpleConditionFactory.py#L30-L46 |
SetBased/py-etlt | etlt/condition/SimpleConditionFactory.py | SimpleConditionFactory.register_scheme | def register_scheme(scheme, constructor):
"""
Registers a scheme.
:param str scheme: The scheme.
:param callable constructor: The SimpleCondition constructor.
"""
if not re.search(r'^[a-z]+$', scheme):
raise ValueError('{0!s} is not a valid scheme'.format(sch... | python | def register_scheme(scheme, constructor):
"""
Registers a scheme.
:param str scheme: The scheme.
:param callable constructor: The SimpleCondition constructor.
"""
if not re.search(r'^[a-z]+$', scheme):
raise ValueError('{0!s} is not a valid scheme'.format(sch... | [
"def",
"register_scheme",
"(",
"scheme",
",",
"constructor",
")",
":",
"if",
"not",
"re",
".",
"search",
"(",
"r'^[a-z]+$'",
",",
"scheme",
")",
":",
"raise",
"ValueError",
"(",
"'{0!s} is not a valid scheme'",
".",
"format",
"(",
"scheme",
")",
")",
"if",
... | Registers a scheme.
:param str scheme: The scheme.
:param callable constructor: The SimpleCondition constructor. | [
"Registers",
"a",
"scheme",
"."
] | train | https://github.com/SetBased/py-etlt/blob/1c5b8ea60293c14f54d7845a9fe5c595021f66f2/etlt/condition/SimpleConditionFactory.py#L50-L63 |
exa-analytics/exa | exa/util/isotopes.py | _create | def _create():
"""Globally called function for creating the isotope/element API."""
def creator(group):
"""Helper function applied to each symbol group of the raw isotope table."""
symbol = group['symbol'].values[0]
try: # Ghosts and custom atoms don't necessarily have an abundance fr... | python | def _create():
"""Globally called function for creating the isotope/element API."""
def creator(group):
"""Helper function applied to each symbol group of the raw isotope table."""
symbol = group['symbol'].values[0]
try: # Ghosts and custom atoms don't necessarily have an abundance fr... | [
"def",
"_create",
"(",
")",
":",
"def",
"creator",
"(",
"group",
")",
":",
"\"\"\"Helper function applied to each symbol group of the raw isotope table.\"\"\"",
"symbol",
"=",
"group",
"[",
"'symbol'",
"]",
".",
"values",
"[",
"0",
"]",
"try",
":",
"# Ghosts and cus... | Globally called function for creating the isotope/element API. | [
"Globally",
"called",
"function",
"for",
"creating",
"the",
"isotope",
"/",
"element",
"API",
"."
] | train | https://github.com/exa-analytics/exa/blob/40fb3c22b531d460dbc51e603de75b856cc28f0d/exa/util/isotopes.py#L124-L154 |
exa-analytics/exa | exa/util/isotopes.py | as_df | def as_df():
"""Return a dataframe of isotopes."""
records = []
for sym, ele in vars(_this).items():
if sym not in ["Element", "Isotope"] and not sym.startswith("_"):
for k, v in vars(ele).items():
if k.startswith("_") and k[1].isdigit():
records.appen... | python | def as_df():
"""Return a dataframe of isotopes."""
records = []
for sym, ele in vars(_this).items():
if sym not in ["Element", "Isotope"] and not sym.startswith("_"):
for k, v in vars(ele).items():
if k.startswith("_") and k[1].isdigit():
records.appen... | [
"def",
"as_df",
"(",
")",
":",
"records",
"=",
"[",
"]",
"for",
"sym",
",",
"ele",
"in",
"vars",
"(",
"_this",
")",
".",
"items",
"(",
")",
":",
"if",
"sym",
"not",
"in",
"[",
"\"Element\"",
",",
"\"Isotope\"",
"]",
"and",
"not",
"sym",
".",
"s... | Return a dataframe of isotopes. | [
"Return",
"a",
"dataframe",
"of",
"isotopes",
"."
] | train | https://github.com/exa-analytics/exa/blob/40fb3c22b531d460dbc51e603de75b856cc28f0d/exa/util/isotopes.py#L157-L165 |
sprymix/metamagic.json | metamagic/json/__init__.py | loadb | def loadb(b):
"""Deserialize ``b`` (instance of ``bytes``) to a Python object."""
assert isinstance(b, (bytes, bytearray))
return std_json.loads(b.decode('utf-8')) | python | def loadb(b):
"""Deserialize ``b`` (instance of ``bytes``) to a Python object."""
assert isinstance(b, (bytes, bytearray))
return std_json.loads(b.decode('utf-8')) | [
"def",
"loadb",
"(",
"b",
")",
":",
"assert",
"isinstance",
"(",
"b",
",",
"(",
"bytes",
",",
"bytearray",
")",
")",
"return",
"std_json",
".",
"loads",
"(",
"b",
".",
"decode",
"(",
"'utf-8'",
")",
")"
] | Deserialize ``b`` (instance of ``bytes``) to a Python object. | [
"Deserialize",
"b",
"(",
"instance",
"of",
"bytes",
")",
"to",
"a",
"Python",
"object",
"."
] | train | https://github.com/sprymix/metamagic.json/blob/c95d3cacd641d433af44f0774f51a085cb4888e6/metamagic/json/__init__.py#L98-L101 |
celliern/triflow | triflow/core/simulation.py | Simulation._compute_one_step | def _compute_one_step(self, t, fields, pars):
"""
Compute one step of the simulation, then update the timers.
"""
fields, pars = self._hook(t, fields, pars)
self.dt = (self.tmax - t
if self.tmax and (t + self.dt >= self.tmax)
else self.dt)
... | python | def _compute_one_step(self, t, fields, pars):
"""
Compute one step of the simulation, then update the timers.
"""
fields, pars = self._hook(t, fields, pars)
self.dt = (self.tmax - t
if self.tmax and (t + self.dt >= self.tmax)
else self.dt)
... | [
"def",
"_compute_one_step",
"(",
"self",
",",
"t",
",",
"fields",
",",
"pars",
")",
":",
"fields",
",",
"pars",
"=",
"self",
".",
"_hook",
"(",
"t",
",",
"fields",
",",
"pars",
")",
"self",
".",
"dt",
"=",
"(",
"self",
".",
"tmax",
"-",
"t",
"i... | Compute one step of the simulation, then update the timers. | [
"Compute",
"one",
"step",
"of",
"the",
"simulation",
"then",
"update",
"the",
"timers",
"."
] | train | https://github.com/celliern/triflow/blob/9522de077c43c8af7d4bf08fbd4ce4b7b480dccb/triflow/core/simulation.py#L210-L226 |
celliern/triflow | triflow/core/simulation.py | Simulation.compute | def compute(self):
"""Generator which yield the actual state of the system every dt.
Yields
------
tuple : t, fields
Actual time and updated fields container.
"""
fields = self.fields
t = self.t
pars = self.parameters
self._started_tim... | python | def compute(self):
"""Generator which yield the actual state of the system every dt.
Yields
------
tuple : t, fields
Actual time and updated fields container.
"""
fields = self.fields
t = self.t
pars = self.parameters
self._started_tim... | [
"def",
"compute",
"(",
"self",
")",
":",
"fields",
"=",
"self",
".",
"fields",
"t",
"=",
"self",
".",
"t",
"pars",
"=",
"self",
".",
"parameters",
"self",
".",
"_started_timestamp",
"=",
"pendulum",
".",
"now",
"(",
")",
"self",
".",
"stream",
".",
... | Generator which yield the actual state of the system every dt.
Yields
------
tuple : t, fields
Actual time and updated fields container. | [
"Generator",
"which",
"yield",
"the",
"actual",
"state",
"of",
"the",
"system",
"every",
"dt",
"."
] | train | https://github.com/celliern/triflow/blob/9522de077c43c8af7d4bf08fbd4ce4b7b480dccb/triflow/core/simulation.py#L228-L261 |
celliern/triflow | triflow/core/simulation.py | Simulation.run | def run(self, progress=True, verbose=False):
"""Compute all steps of the simulation. Be careful: if tmax is not set,
this function will result in an infinit loop.
Returns
-------
(t, fields):
last time and result fields.
"""
total_iter = int((self.tm... | python | def run(self, progress=True, verbose=False):
"""Compute all steps of the simulation. Be careful: if tmax is not set,
this function will result in an infinit loop.
Returns
-------
(t, fields):
last time and result fields.
"""
total_iter = int((self.tm... | [
"def",
"run",
"(",
"self",
",",
"progress",
"=",
"True",
",",
"verbose",
"=",
"False",
")",
":",
"total_iter",
"=",
"int",
"(",
"(",
"self",
".",
"tmax",
"//",
"self",
".",
"user_dt",
")",
"if",
"self",
".",
"tmax",
"else",
"None",
")",
"log",
"=... | Compute all steps of the simulation. Be careful: if tmax is not set,
this function will result in an infinit loop.
Returns
-------
(t, fields):
last time and result fields. | [
"Compute",
"all",
"steps",
"of",
"the",
"simulation",
".",
"Be",
"careful",
":",
"if",
"tmax",
"is",
"not",
"set",
"this",
"function",
"will",
"result",
"in",
"an",
"infinit",
"loop",
"."
] | train | https://github.com/celliern/triflow/blob/9522de077c43c8af7d4bf08fbd4ce4b7b480dccb/triflow/core/simulation.py#L268-L295 |
celliern/triflow | triflow/core/simulation.py | Simulation.attach_container | def attach_container(self, path=None, save="all",
mode="w", nbuffer=50, force=False):
"""add a Container to the simulation which allows some
persistance to the simulation.
Parameters
----------
path : str or None (default: None)
path for the ... | python | def attach_container(self, path=None, save="all",
mode="w", nbuffer=50, force=False):
"""add a Container to the simulation which allows some
persistance to the simulation.
Parameters
----------
path : str or None (default: None)
path for the ... | [
"def",
"attach_container",
"(",
"self",
",",
"path",
"=",
"None",
",",
"save",
"=",
"\"all\"",
",",
"mode",
"=",
"\"w\"",
",",
"nbuffer",
"=",
"50",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"_container",
"=",
"TriflowContainer",
"(",
"\"%s/%s... | add a Container to the simulation which allows some
persistance to the simulation.
Parameters
----------
path : str or None (default: None)
path for the container. If None (the default), the data lives only
in memory (and are available with `simulation.container`... | [
"add",
"a",
"Container",
"to",
"the",
"simulation",
"which",
"allows",
"some",
"persistance",
"to",
"the",
"simulation",
"."
] | train | https://github.com/celliern/triflow/blob/9522de077c43c8af7d4bf08fbd4ce4b7b480dccb/triflow/core/simulation.py#L352-L381 |
celliern/triflow | triflow/core/simulation.py | Simulation.add_post_process | def add_post_process(self, name, post_process, description=""):
"""add a post-process
Parameters
----------
name : str
name of the post-traitment
post_process : callback (function of a class with a __call__ method
or a streamz.Stream)... | python | def add_post_process(self, name, post_process, description=""):
"""add a post-process
Parameters
----------
name : str
name of the post-traitment
post_process : callback (function of a class with a __call__ method
or a streamz.Stream)... | [
"def",
"add_post_process",
"(",
"self",
",",
"name",
",",
"post_process",
",",
"description",
"=",
"\"\"",
")",
":",
"self",
".",
"_pprocesses",
".",
"append",
"(",
"PostProcess",
"(",
"name",
"=",
"name",
",",
"function",
"=",
"post_process",
",",
"descri... | add a post-process
Parameters
----------
name : str
name of the post-traitment
post_process : callback (function of a class with a __call__ method
or a streamz.Stream).
this callback have to accept the simulation state as paramete... | [
"add",
"a",
"post",
"-",
"process"
] | train | https://github.com/celliern/triflow/blob/9522de077c43c8af7d4bf08fbd4ce4b7b480dccb/triflow/core/simulation.py#L399-L420 |
celliern/triflow | triflow/core/simulation.py | Simulation.remove_post_process | def remove_post_process(self, name):
"""remove a post-process
Parameters
----------
name : str
name of the post-process to remove.
"""
self._pprocesses = [post_process
for post_process in self._pprocesses
... | python | def remove_post_process(self, name):
"""remove a post-process
Parameters
----------
name : str
name of the post-process to remove.
"""
self._pprocesses = [post_process
for post_process in self._pprocesses
... | [
"def",
"remove_post_process",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_pprocesses",
"=",
"[",
"post_process",
"for",
"post_process",
"in",
"self",
".",
"_pprocesses",
"if",
"post_process",
".",
"name",
"!=",
"name",
"]"
] | remove a post-process
Parameters
----------
name : str
name of the post-process to remove. | [
"remove",
"a",
"post",
"-",
"process"
] | train | https://github.com/celliern/triflow/blob/9522de077c43c8af7d4bf08fbd4ce4b7b480dccb/triflow/core/simulation.py#L422-L432 |
ionelmc/python-cogen | cogen/core/queue.py | Queue.task_done | def task_done(self, **kws):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently... | python | def task_done(self, **kws):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently... | [
"def",
"task_done",
"(",
"self",
",",
"*",
"*",
"kws",
")",
":",
"unfinished",
"=",
"self",
".",
"unfinished_tasks",
"-",
"1",
"op",
"=",
"None",
"if",
"unfinished",
"<=",
"0",
":",
"if",
"unfinished",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'tas... | Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items... | [
"Indicate",
"that",
"a",
"formerly",
"enqueued",
"task",
"is",
"complete",
".",
"Used",
"by",
"Queue",
"consumer",
"threads",
".",
"For",
"each",
"get",
"()",
"used",
"to",
"fetch",
"a",
"task",
"a",
"subsequent",
"call",
"to",
"task_done",
"()",
"tells",
... | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/queue.py#L194-L215 |
ionelmc/python-cogen | cogen/core/queue.py | Queue.put | def put(self, item, block=True, **kws):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
... | python | def put(self, item, block=True, **kws):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
... | [
"def",
"put",
"(",
"self",
",",
"item",
",",
"block",
"=",
"True",
",",
"*",
"*",
"kws",
")",
":",
"return",
"QPut",
"(",
"self",
",",
"item",
",",
"block",
",",
"*",
"*",
"kws",
")"
] | Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available wi... | [
"Put",
"an",
"item",
"into",
"the",
"queue",
".",
"If",
"optional",
"args",
"block",
"is",
"true",
"and",
"timeout",
"is",
"None",
"(",
"the",
"default",
")",
"block",
"if",
"necessary",
"until",
"a",
"free",
"slot",
"is",
"available",
".",
"If",
"time... | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/queue.py#L241-L252 |
alexmojaki/outdated | outdated/utils.py | cache_file | def cache_file(package, mode):
"""
Yields a file-like object for the purpose of writing to or
reading from the cache.
The code:
with cache_file(...) as f:
# do stuff with f
is guaranteed to convert any exceptions to warnings (*),
both in the cache_file(...) call and the 'd... | python | def cache_file(package, mode):
"""
Yields a file-like object for the purpose of writing to or
reading from the cache.
The code:
with cache_file(...) as f:
# do stuff with f
is guaranteed to convert any exceptions to warnings (*),
both in the cache_file(...) call and the 'd... | [
"def",
"cache_file",
"(",
"package",
",",
"mode",
")",
":",
"f",
"=",
"DummyFile",
"(",
")",
"# We have to wrap the whole function body in this block to guarantee",
"# catching all exceptions. In particular the yield needs to be inside",
"# to catch exceptions coming from the with bloc... | Yields a file-like object for the purpose of writing to or
reading from the cache.
The code:
with cache_file(...) as f:
# do stuff with f
is guaranteed to convert any exceptions to warnings (*),
both in the cache_file(...) call and the 'do stuff with f'
block.
The file is... | [
"Yields",
"a",
"file",
"-",
"like",
"object",
"for",
"the",
"purpose",
"of",
"writing",
"to",
"or",
"reading",
"from",
"the",
"cache",
"."
] | train | https://github.com/alexmojaki/outdated/blob/565bb3fe1adc30da5e50249912cd2ac494662659/outdated/utils.py#L37-L76 |
alexmojaki/outdated | outdated/utils.py | exception_to_warning | def exception_to_warning(description, category, always_raise=False):
"""
Catches any exceptions that happen in the corresponding with block
and instead emits a warning of the given category,
unless always_raise is True or the environment variable
OUTDATED_RAISE_EXCEPTION is set to 1, in which caise ... | python | def exception_to_warning(description, category, always_raise=False):
"""
Catches any exceptions that happen in the corresponding with block
and instead emits a warning of the given category,
unless always_raise is True or the environment variable
OUTDATED_RAISE_EXCEPTION is set to 1, in which caise ... | [
"def",
"exception_to_warning",
"(",
"description",
",",
"category",
",",
"always_raise",
"=",
"False",
")",
":",
"try",
":",
"yield",
"except",
"Exception",
":",
"# We check for the presence of various globals because we may be seeing the death",
"# of the process if this is in... | Catches any exceptions that happen in the corresponding with block
and instead emits a warning of the given category,
unless always_raise is True or the environment variable
OUTDATED_RAISE_EXCEPTION is set to 1, in which caise the exception
will not be caught. | [
"Catches",
"any",
"exceptions",
"that",
"happen",
"in",
"the",
"corresponding",
"with",
"block",
"and",
"instead",
"emits",
"a",
"warning",
"of",
"the",
"given",
"category",
"unless",
"always_raise",
"is",
"True",
"or",
"the",
"environment",
"variable",
"OUTDATE... | train | https://github.com/alexmojaki/outdated/blob/565bb3fe1adc30da5e50249912cd2ac494662659/outdated/utils.py#L84-L108 |
petebachant/Nortek-Python | nortek/controls.py | PdControl.transmit_length | def transmit_length(self, val=3):
"""Sets transmit length."""
if self.instrument == "Vectrino" and type(val) is float:
if val == 0.3:
self.pdx.TransmitLength = 0
elif val == 0.6:
self.pdx.TransmitLength = 1
elif val == 1.2:
... | python | def transmit_length(self, val=3):
"""Sets transmit length."""
if self.instrument == "Vectrino" and type(val) is float:
if val == 0.3:
self.pdx.TransmitLength = 0
elif val == 0.6:
self.pdx.TransmitLength = 1
elif val == 1.2:
... | [
"def",
"transmit_length",
"(",
"self",
",",
"val",
"=",
"3",
")",
":",
"if",
"self",
".",
"instrument",
"==",
"\"Vectrino\"",
"and",
"type",
"(",
"val",
")",
"is",
"float",
":",
"if",
"val",
"==",
"0.3",
":",
"self",
".",
"pdx",
".",
"TransmitLength"... | Sets transmit length. | [
"Sets",
"transmit",
"length",
"."
] | train | https://github.com/petebachant/Nortek-Python/blob/6c979662cf62c11ad5899ccc5e53365c87e5be02/nortek/controls.py#L186-L204 |
petebachant/Nortek-Python | nortek/controls.py | PdControl.sampling_volume | def sampling_volume(self, val):
"""Sets sampling volume."""
if self.instrument == "Vectrino" and type(val) is float:
if val == 2.5:
self.pdx.SamplingVolume = 0
elif val == 4.0:
self.pdx.SamplingVolume = 1
elif val == 5.5:
... | python | def sampling_volume(self, val):
"""Sets sampling volume."""
if self.instrument == "Vectrino" and type(val) is float:
if val == 2.5:
self.pdx.SamplingVolume = 0
elif val == 4.0:
self.pdx.SamplingVolume = 1
elif val == 5.5:
... | [
"def",
"sampling_volume",
"(",
"self",
",",
"val",
")",
":",
"if",
"self",
".",
"instrument",
"==",
"\"Vectrino\"",
"and",
"type",
"(",
"val",
")",
"is",
"float",
":",
"if",
"val",
"==",
"2.5",
":",
"self",
".",
"pdx",
".",
"SamplingVolume",
"=",
"0"... | Sets sampling volume. | [
"Sets",
"sampling",
"volume",
"."
] | train | https://github.com/petebachant/Nortek-Python/blob/6c979662cf62c11ad5899ccc5e53365c87e5be02/nortek/controls.py#L210-L228 |
petebachant/Nortek-Python | nortek/controls.py | PdControl.sound_speed_mode | def sound_speed_mode(self, mode):
"""Sets sound speed mode; 0 or "measured" for measured; 1 or "fixed"
for fixed."""
if mode == "measured":
mode = 0
if mode == "fixed":
mode = 1
self.pdx.SoundSpeedMode = mode | python | def sound_speed_mode(self, mode):
"""Sets sound speed mode; 0 or "measured" for measured; 1 or "fixed"
for fixed."""
if mode == "measured":
mode = 0
if mode == "fixed":
mode = 1
self.pdx.SoundSpeedMode = mode | [
"def",
"sound_speed_mode",
"(",
"self",
",",
"mode",
")",
":",
"if",
"mode",
"==",
"\"measured\"",
":",
"mode",
"=",
"0",
"if",
"mode",
"==",
"\"fixed\"",
":",
"mode",
"=",
"1",
"self",
".",
"pdx",
".",
"SoundSpeedMode",
"=",
"mode"
] | Sets sound speed mode; 0 or "measured" for measured; 1 or "fixed"
for fixed. | [
"Sets",
"sound",
"speed",
"mode",
";",
"0",
"or",
"measured",
"for",
"measured",
";",
"1",
"or",
"fixed",
"for",
"fixed",
"."
] | train | https://github.com/petebachant/Nortek-Python/blob/6c979662cf62c11ad5899ccc5e53365c87e5be02/nortek/controls.py#L235-L242 |
petebachant/Nortek-Python | nortek/controls.py | PdControl.sound_speed | def sound_speed(self, value):
"""Sets the sound speed in m/s. Default is 1525.0. If this function is
called, `sound_speed_mode` will be set to fixed."""
if not self.sound_speed_mode:
self.sound_speed_mode = 1
self.pdx.SoundSpeed = float(value) | python | def sound_speed(self, value):
"""Sets the sound speed in m/s. Default is 1525.0. If this function is
called, `sound_speed_mode` will be set to fixed."""
if not self.sound_speed_mode:
self.sound_speed_mode = 1
self.pdx.SoundSpeed = float(value) | [
"def",
"sound_speed",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"sound_speed_mode",
":",
"self",
".",
"sound_speed_mode",
"=",
"1",
"self",
".",
"pdx",
".",
"SoundSpeed",
"=",
"float",
"(",
"value",
")"
] | Sets the sound speed in m/s. Default is 1525.0. If this function is
called, `sound_speed_mode` will be set to fixed. | [
"Sets",
"the",
"sound",
"speed",
"in",
"m",
"/",
"s",
".",
"Default",
"is",
"1525",
".",
"0",
".",
"If",
"this",
"function",
"is",
"called",
"sound_speed_mode",
"will",
"be",
"set",
"to",
"fixed",
"."
] | train | https://github.com/petebachant/Nortek-Python/blob/6c979662cf62c11ad5899ccc5e53365c87e5be02/nortek/controls.py#L249-L254 |
petebachant/Nortek-Python | nortek/controls.py | PdControl.power_level | def power_level(self, val):
"""Sets the power level according to the index or string.
0 = High
1 = HighLow
2 = LowHigh
3 = Low"""
if val in [0, 1, 2, 3]:
self.pdx.PowerLevel = val
elif type(val) is str:
if val.lower() == "high":
... | python | def power_level(self, val):
"""Sets the power level according to the index or string.
0 = High
1 = HighLow
2 = LowHigh
3 = Low"""
if val in [0, 1, 2, 3]:
self.pdx.PowerLevel = val
elif type(val) is str:
if val.lower() == "high":
... | [
"def",
"power_level",
"(",
"self",
",",
"val",
")",
":",
"if",
"val",
"in",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
"]",
":",
"self",
".",
"pdx",
".",
"PowerLevel",
"=",
"val",
"elif",
"type",
"(",
"val",
")",
"is",
"str",
":",
"if",
"val",
... | Sets the power level according to the index or string.
0 = High
1 = HighLow
2 = LowHigh
3 = Low | [
"Sets",
"the",
"power",
"level",
"according",
"to",
"the",
"index",
"or",
"string",
".",
"0",
"=",
"High",
"1",
"=",
"HighLow",
"2",
"=",
"LowHigh",
"3",
"=",
"Low"
] | train | https://github.com/petebachant/Nortek-Python/blob/6c979662cf62c11ad5899ccc5e53365c87e5be02/nortek/controls.py#L277-L295 |
petebachant/Nortek-Python | nortek/controls.py | PdControl.coordinate_system | def coordinate_system(self, coordsys):
"""Sets instrument coordinate system. Accepts an int or string."""
if coordsys.upper() == "ENU":
ncs = 0
elif coordsys.upper() == "XYZ":
ncs = 1
elif coordsys.upper() == "BEAM":
ncs = 2
elif coordsys in [0... | python | def coordinate_system(self, coordsys):
"""Sets instrument coordinate system. Accepts an int or string."""
if coordsys.upper() == "ENU":
ncs = 0
elif coordsys.upper() == "XYZ":
ncs = 1
elif coordsys.upper() == "BEAM":
ncs = 2
elif coordsys in [0... | [
"def",
"coordinate_system",
"(",
"self",
",",
"coordsys",
")",
":",
"if",
"coordsys",
".",
"upper",
"(",
")",
"==",
"\"ENU\"",
":",
"ncs",
"=",
"0",
"elif",
"coordsys",
".",
"upper",
"(",
")",
"==",
"\"XYZ\"",
":",
"ncs",
"=",
"1",
"elif",
"coordsys"... | Sets instrument coordinate system. Accepts an int or string. | [
"Sets",
"instrument",
"coordinate",
"system",
".",
"Accepts",
"an",
"int",
"or",
"string",
"."
] | train | https://github.com/petebachant/Nortek-Python/blob/6c979662cf62c11ad5899ccc5e53365c87e5be02/nortek/controls.py#L332-L344 |
petebachant/Nortek-Python | nortek/controls.py | PdControl.start_disk_recording | def start_disk_recording(self, filename, autoname=False):
"""Starts data recording to disk. Specify the filename without extension.
If autoname = True a new file will be opened for data recording each time
the specified time interval has elapsed. The current date and time is then
auto... | python | def start_disk_recording(self, filename, autoname=False):
"""Starts data recording to disk. Specify the filename without extension.
If autoname = True a new file will be opened for data recording each time
the specified time interval has elapsed. The current date and time is then
auto... | [
"def",
"start_disk_recording",
"(",
"self",
",",
"filename",
",",
"autoname",
"=",
"False",
")",
":",
"self",
".",
"pdx",
".",
"StartDiskRecording",
"(",
"filename",
",",
"autoname",
")"
] | Starts data recording to disk. Specify the filename without extension.
If autoname = True a new file will be opened for data recording each time
the specified time interval has elapsed. The current date and time is then
automatically added to the filename. | [
"Starts",
"data",
"recording",
"to",
"disk",
".",
"Specify",
"the",
"filename",
"without",
"extension",
".",
"If",
"autoname",
"=",
"True",
"a",
"new",
"file",
"will",
"be",
"opened",
"for",
"data",
"recording",
"each",
"time",
"the",
"specified",
"time",
... | train | https://github.com/petebachant/Nortek-Python/blob/6c979662cf62c11ad5899ccc5e53365c87e5be02/nortek/controls.py#L359-L364 |
petebachant/Nortek-Python | nortek/controls.py | PdControl.sampling_volume_value | def sampling_volume_value(self):
"""Returns the device samping volume value in m."""
svi = self.pdx.SamplingVolume
tli = self.pdx.TransmitLength
return self._sampling_volume_value(svi, tli) | python | def sampling_volume_value(self):
"""Returns the device samping volume value in m."""
svi = self.pdx.SamplingVolume
tli = self.pdx.TransmitLength
return self._sampling_volume_value(svi, tli) | [
"def",
"sampling_volume_value",
"(",
"self",
")",
":",
"svi",
"=",
"self",
".",
"pdx",
".",
"SamplingVolume",
"tli",
"=",
"self",
".",
"pdx",
".",
"TransmitLength",
"return",
"self",
".",
"_sampling_volume_value",
"(",
"svi",
",",
"tli",
")"
] | Returns the device samping volume value in m. | [
"Returns",
"the",
"device",
"samping",
"volume",
"value",
"in",
"m",
"."
] | train | https://github.com/petebachant/Nortek-Python/blob/6c979662cf62c11ad5899ccc5e53365c87e5be02/nortek/controls.py#L409-L413 |
Lucretiel/autocommand | src/autocommand/autoasync.py | _launch_forever_coro | def _launch_forever_coro(coro, args, kwargs, loop):
'''
This helper function launches an async main function that was tagged with
forever=True. There are two possibilities:
- The function is a normal function, which handles initializing the event
loop, which is then run forever
- The function... | python | def _launch_forever_coro(coro, args, kwargs, loop):
'''
This helper function launches an async main function that was tagged with
forever=True. There are two possibilities:
- The function is a normal function, which handles initializing the event
loop, which is then run forever
- The function... | [
"def",
"_launch_forever_coro",
"(",
"coro",
",",
"args",
",",
"kwargs",
",",
"loop",
")",
":",
"# Personal note: I consider this an antipattern, as it relies on the use of",
"# unowned resources. The setup function dumps some stuff into the event",
"# loop where it just whirls in the eth... | This helper function launches an async main function that was tagged with
forever=True. There are two possibilities:
- The function is a normal function, which handles initializing the event
loop, which is then run forever
- The function is a coroutine, which needs to be scheduled in the event
... | [
"This",
"helper",
"function",
"launches",
"an",
"async",
"main",
"function",
"that",
"was",
"tagged",
"with",
"forever",
"=",
"True",
".",
"There",
"are",
"two",
"possibilities",
":"
] | train | https://github.com/Lucretiel/autocommand/blob/bd3c58a210fdfcc943c729cc5579033add68d0b3/src/autocommand/autoasync.py#L23-L51 |
Lucretiel/autocommand | src/autocommand/autoasync.py | autoasync | def autoasync(coro=None, *, loop=None, forever=False, pass_loop=False):
'''
Convert an asyncio coroutine into a function which, when called, is
evaluted in an event loop, and the return value returned. This is intented
to make it easy to write entry points into asyncio coroutines, which
otherwise ne... | python | def autoasync(coro=None, *, loop=None, forever=False, pass_loop=False):
'''
Convert an asyncio coroutine into a function which, when called, is
evaluted in an event loop, and the return value returned. This is intented
to make it easy to write entry points into asyncio coroutines, which
otherwise ne... | [
"def",
"autoasync",
"(",
"coro",
"=",
"None",
",",
"*",
",",
"loop",
"=",
"None",
",",
"forever",
"=",
"False",
",",
"pass_loop",
"=",
"False",
")",
":",
"if",
"coro",
"is",
"None",
":",
"return",
"lambda",
"c",
":",
"autoasync",
"(",
"c",
",",
"... | Convert an asyncio coroutine into a function which, when called, is
evaluted in an event loop, and the return value returned. This is intented
to make it easy to write entry points into asyncio coroutines, which
otherwise need to be explictly evaluted with an event loop's
run_until_complete.
If `lo... | [
"Convert",
"an",
"asyncio",
"coroutine",
"into",
"a",
"function",
"which",
"when",
"called",
"is",
"evaluted",
"in",
"an",
"event",
"loop",
"and",
"the",
"return",
"value",
"returned",
".",
"This",
"is",
"intented",
"to",
"make",
"it",
"easy",
"to",
"write... | train | https://github.com/Lucretiel/autocommand/blob/bd3c58a210fdfcc943c729cc5579033add68d0b3/src/autocommand/autoasync.py#L54-L140 |
Lucretiel/autocommand | src/autocommand/automain.py | automain | def automain(module, *, args=(), kwargs=None):
'''
This decorator automatically invokes a function if the module is being run
as the "__main__" module. Optionally, provide args or kwargs with which to
call the function. If `module` is "__main__", the function is called, and
the program is `sys.exit`... | python | def automain(module, *, args=(), kwargs=None):
'''
This decorator automatically invokes a function if the module is being run
as the "__main__" module. Optionally, provide args or kwargs with which to
call the function. If `module` is "__main__", the function is called, and
the program is `sys.exit`... | [
"def",
"automain",
"(",
"module",
",",
"*",
",",
"args",
"=",
"(",
")",
",",
"kwargs",
"=",
"None",
")",
":",
"# Check that @automain(...) was called, rather than @automain",
"if",
"callable",
"(",
"module",
")",
":",
"raise",
"AutomainRequiresModuleError",
"(",
... | This decorator automatically invokes a function if the module is being run
as the "__main__" module. Optionally, provide args or kwargs with which to
call the function. If `module` is "__main__", the function is called, and
the program is `sys.exit`ed with the return value. You can also pass `True`
to c... | [
"This",
"decorator",
"automatically",
"invokes",
"a",
"function",
"if",
"the",
"module",
"is",
"being",
"run",
"as",
"the",
"__main__",
"module",
".",
"Optionally",
"provide",
"args",
"or",
"kwargs",
"with",
"which",
"to",
"call",
"the",
"function",
".",
"If... | train | https://github.com/Lucretiel/autocommand/blob/bd3c58a210fdfcc943c729cc5579033add68d0b3/src/autocommand/automain.py#L26-L59 |
fp12/achallonge | challonge/match.py | Match.report_winner | async def report_winner(self, winner: Participant, scores_csv: str):
""" report scores and give a winner
|methcoro|
Args:
winner: :class:Participant instance
scores_csv: Comma separated set/game scores with player 1 score first (e.g. "1-3,3-0,3-2")
Raises:
... | python | async def report_winner(self, winner: Participant, scores_csv: str):
""" report scores and give a winner
|methcoro|
Args:
winner: :class:Participant instance
scores_csv: Comma separated set/game scores with player 1 score first (e.g. "1-3,3-0,3-2")
Raises:
... | [
"async",
"def",
"report_winner",
"(",
"self",
",",
"winner",
":",
"Participant",
",",
"scores_csv",
":",
"str",
")",
":",
"await",
"self",
".",
"_report",
"(",
"scores_csv",
",",
"winner",
".",
"_id",
")"
] | report scores and give a winner
|methcoro|
Args:
winner: :class:Participant instance
scores_csv: Comma separated set/game scores with player 1 score first (e.g. "1-3,3-0,3-2")
Raises:
ValueError: scores_csv has a wrong format
APIException | [
"report",
"scores",
"and",
"give",
"a",
"winner"
] | train | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/match.py#L88-L102 |
fp12/achallonge | challonge/match.py | Match.reopen | async def reopen(self):
""" Reopens a match that was marked completed, automatically resetting matches that follow it
|methcoro|
Raises:
APIException
"""
res = await self.connection('POST', 'tournaments/{}/matches/{}/reopen'.format(self._tournament_id, self._id))
... | python | async def reopen(self):
""" Reopens a match that was marked completed, automatically resetting matches that follow it
|methcoro|
Raises:
APIException
"""
res = await self.connection('POST', 'tournaments/{}/matches/{}/reopen'.format(self._tournament_id, self._id))
... | [
"async",
"def",
"reopen",
"(",
"self",
")",
":",
"res",
"=",
"await",
"self",
".",
"connection",
"(",
"'POST'",
",",
"'tournaments/{}/matches/{}/reopen'",
".",
"format",
"(",
"self",
".",
"_tournament_id",
",",
"self",
".",
"_id",
")",
")",
"self",
".",
... | Reopens a match that was marked completed, automatically resetting matches that follow it
|methcoro|
Raises:
APIException | [
"Reopens",
"a",
"match",
"that",
"was",
"marked",
"completed",
"automatically",
"resetting",
"matches",
"that",
"follow",
"it"
] | train | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/match.py#L118-L128 |
fp12/achallonge | challonge/match.py | Match.change_votes | async def change_votes(self, player1_votes: int = None, player2_votes: int = None, add: bool = False):
""" change the votes for either player
|methcoro|
The votes will be overriden by default,
If `add` is set to True, another API request call will be made to ensure the local is up to da... | python | async def change_votes(self, player1_votes: int = None, player2_votes: int = None, add: bool = False):
""" change the votes for either player
|methcoro|
The votes will be overriden by default,
If `add` is set to True, another API request call will be made to ensure the local is up to da... | [
"async",
"def",
"change_votes",
"(",
"self",
",",
"player1_votes",
":",
"int",
"=",
"None",
",",
"player2_votes",
":",
"int",
"=",
"None",
",",
"add",
":",
"bool",
"=",
"False",
")",
":",
"assert_or_raise",
"(",
"player1_votes",
"is",
"not",
"None",
"or"... | change the votes for either player
|methcoro|
The votes will be overriden by default,
If `add` is set to True, another API request call will be made to ensure the local is up to date with
the Challonge server. Then the votes given in argument will be added to those on the server
... | [
"change",
"the",
"votes",
"for",
"either",
"player"
] | train | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/match.py#L130-L170 |
fp12/achallonge | challonge/match.py | Match.attach_file | async def attach_file(self, file_path: str, description: str = None) -> Attachment:
""" add a file as an attachment
|methcoro|
Warning:
|unstable|
Args:
file_path: path to the file you want to add
description: *optional* description for your attachm... | python | async def attach_file(self, file_path: str, description: str = None) -> Attachment:
""" add a file as an attachment
|methcoro|
Warning:
|unstable|
Args:
file_path: path to the file you want to add
description: *optional* description for your attachm... | [
"async",
"def",
"attach_file",
"(",
"self",
",",
"file_path",
":",
"str",
",",
"description",
":",
"str",
"=",
"None",
")",
"->",
"Attachment",
":",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"f",
":",
"return",
"await",
"self",
".",
"... | add a file as an attachment
|methcoro|
Warning:
|unstable|
Args:
file_path: path to the file you want to add
description: *optional* description for your attachment
Returns:
Attachment:
Raises:
ValueError: file_path... | [
"add",
"a",
"file",
"as",
"an",
"attachment"
] | train | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/match.py#L182-L203 |
fp12/achallonge | challonge/match.py | Match.attach_url | async def attach_url(self, url: str, description: str = None) -> Attachment:
""" add an url as an attachment
|methcoro|
Args:
url: url you want to add
description: *optional* description for your attachment
Returns:
Attachment:
Raises:
... | python | async def attach_url(self, url: str, description: str = None) -> Attachment:
""" add an url as an attachment
|methcoro|
Args:
url: url you want to add
description: *optional* description for your attachment
Returns:
Attachment:
Raises:
... | [
"async",
"def",
"attach_url",
"(",
"self",
",",
"url",
":",
"str",
",",
"description",
":",
"str",
"=",
"None",
")",
"->",
"Attachment",
":",
"return",
"await",
"self",
".",
"_attach",
"(",
"url",
"=",
"url",
",",
"description",
"=",
"description",
")"... | add an url as an attachment
|methcoro|
Args:
url: url you want to add
description: *optional* description for your attachment
Returns:
Attachment:
Raises:
ValueError: url must not be None
APIException | [
"add",
"an",
"url",
"as",
"an",
"attachment"
] | train | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/match.py#L205-L222 |
fp12/achallonge | challonge/match.py | Match.destroy_attachment | async def destroy_attachment(self, a: Attachment):
""" destroy a match attachment
|methcoro|
Args:
a: the attachment you want to destroy
Raises:
APIException
"""
await self.connection('DELETE', 'tournaments/{}/matches/{}/attachments/{}'.format(... | python | async def destroy_attachment(self, a: Attachment):
""" destroy a match attachment
|methcoro|
Args:
a: the attachment you want to destroy
Raises:
APIException
"""
await self.connection('DELETE', 'tournaments/{}/matches/{}/attachments/{}'.format(... | [
"async",
"def",
"destroy_attachment",
"(",
"self",
",",
"a",
":",
"Attachment",
")",
":",
"await",
"self",
".",
"connection",
"(",
"'DELETE'",
",",
"'tournaments/{}/matches/{}/attachments/{}'",
".",
"format",
"(",
"self",
".",
"_tournament_id",
",",
"self",
".",... | destroy a match attachment
|methcoro|
Args:
a: the attachment you want to destroy
Raises:
APIException | [
"destroy",
"a",
"match",
"attachment"
] | train | https://github.com/fp12/achallonge/blob/25780b3c48b66400a50ff9f884e4287afd4c89e4/challonge/match.py#L242-L256 |
yatiml/yatiml | yatiml/introspection.py | class_subobjects | def class_subobjects(
class_: Type) -> Generator[Tuple[str, Type, bool], None, None]:
"""Find the aggregated subobjects of an object.
These are the public attributes.
Args:
class_: The class whose subobjects to return.
Yields:
Tuples (name, type, required) describing subobject... | python | def class_subobjects(
class_: Type) -> Generator[Tuple[str, Type, bool], None, None]:
"""Find the aggregated subobjects of an object.
These are the public attributes.
Args:
class_: The class whose subobjects to return.
Yields:
Tuples (name, type, required) describing subobject... | [
"def",
"class_subobjects",
"(",
"class_",
":",
"Type",
")",
"->",
"Generator",
"[",
"Tuple",
"[",
"str",
",",
"Type",
",",
"bool",
"]",
",",
"None",
",",
"None",
"]",
":",
"argspec",
"=",
"inspect",
".",
"getfullargspec",
"(",
"class_",
".",
"__init__"... | Find the aggregated subobjects of an object.
These are the public attributes.
Args:
class_: The class whose subobjects to return.
Yields:
Tuples (name, type, required) describing subobjects. | [
"Find",
"the",
"aggregated",
"subobjects",
"of",
"an",
"object",
"."
] | train | https://github.com/yatiml/yatiml/blob/4f55c058b72388350f0af3076ac3ea9bc1c142b0/yatiml/introspection.py#L5-L28 |
exa-analytics/exa | exa/util/io.py | read_tarball | def read_tarball(path, shortkey=False, classes=Editor):
"""
Read a (possibly compressed) tarball archive and return a dictionary of
editors.
.. code-block:: python
eds = read_tarball(path, classes=MyEditor) # All files read as type MyEditor
# Only read the special file as type MyEdi... | python | def read_tarball(path, shortkey=False, classes=Editor):
"""
Read a (possibly compressed) tarball archive and return a dictionary of
editors.
.. code-block:: python
eds = read_tarball(path, classes=MyEditor) # All files read as type MyEditor
# Only read the special file as type MyEdi... | [
"def",
"read_tarball",
"(",
"path",
",",
"shortkey",
"=",
"False",
",",
"classes",
"=",
"Editor",
")",
":",
"editors",
"=",
"{",
"}",
"with",
"tarfile",
".",
"open",
"(",
"path",
")",
"as",
"tar",
":",
"for",
"member",
"in",
"tar",
".",
"getmembers",... | Read a (possibly compressed) tarball archive and return a dictionary of
editors.
.. code-block:: python
eds = read_tarball(path, classes=MyEditor) # All files read as type MyEditor
# Only read the special file as type MyEditor (default to Editor)
eds = read_tarball(path.bz2, classes... | [
"Read",
"a",
"(",
"possibly",
"compressed",
")",
"tarball",
"archive",
"and",
"return",
"a",
"dictionary",
"of",
"editors",
"."
] | train | https://github.com/exa-analytics/exa/blob/40fb3c22b531d460dbc51e603de75b856cc28f0d/exa/util/io.py#L13-L49 |
cknoll/ipydex | ipydex/core.py | format_frameinfo | def format_frameinfo(fi):
"""
Takes a frameinfo object (from the inspect module)
returns a properly formated string
"""
s1 = "{0}:{1}".format(fi.filename, fi.lineno)
s2 = "function:{0}, code_context:".format(fi.function)
if fi.code_context:
s3 = fi.code_context[0]
else:
... | python | def format_frameinfo(fi):
"""
Takes a frameinfo object (from the inspect module)
returns a properly formated string
"""
s1 = "{0}:{1}".format(fi.filename, fi.lineno)
s2 = "function:{0}, code_context:".format(fi.function)
if fi.code_context:
s3 = fi.code_context[0]
else:
... | [
"def",
"format_frameinfo",
"(",
"fi",
")",
":",
"s1",
"=",
"\"{0}:{1}\"",
".",
"format",
"(",
"fi",
".",
"filename",
",",
"fi",
".",
"lineno",
")",
"s2",
"=",
"\"function:{0}, code_context:\"",
".",
"format",
"(",
"fi",
".",
"function",
")",
"if",
"fi... | Takes a frameinfo object (from the inspect module)
returns a properly formated string | [
"Takes",
"a",
"frameinfo",
"object",
"(",
"from",
"the",
"inspect",
"module",
")"
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L105-L118 |
cknoll/ipydex | ipydex/core.py | get_frame_list | def get_frame_list():
"""
Create the list of frames
"""
# TODO: use this function in IPS below (less code duplication)
frame_info_list = []
frame_list = []
frame = inspect.currentframe()
while frame is not None:
frame_list.append(frame)
info = inspect.getframeinfo(frame... | python | def get_frame_list():
"""
Create the list of frames
"""
# TODO: use this function in IPS below (less code duplication)
frame_info_list = []
frame_list = []
frame = inspect.currentframe()
while frame is not None:
frame_list.append(frame)
info = inspect.getframeinfo(frame... | [
"def",
"get_frame_list",
"(",
")",
":",
"# TODO: use this function in IPS below (less code duplication)",
"frame_info_list",
"=",
"[",
"]",
"frame_list",
"=",
"[",
"]",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"while",
"frame",
"is",
"not",
"None",
... | Create the list of frames | [
"Create",
"the",
"list",
"of",
"frames"
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L121-L141 |
cknoll/ipydex | ipydex/core.py | IPS | def IPS(copy_namespaces=True, overwrite_globals=False):
"""Starts IPython embedded shell. This is similar to IPython.embed() but with some
additional features:
1. Print a list of the calling frames before entering the prompt
2. (optionally) copy local name space to global one to prevent certain IPython... | python | def IPS(copy_namespaces=True, overwrite_globals=False):
"""Starts IPython embedded shell. This is similar to IPython.embed() but with some
additional features:
1. Print a list of the calling frames before entering the prompt
2. (optionally) copy local name space to global one to prevent certain IPython... | [
"def",
"IPS",
"(",
"copy_namespaces",
"=",
"True",
",",
"overwrite_globals",
"=",
"False",
")",
":",
"# let the user know, where this shell is 'waking up'",
"# construct frame list",
"# this will be printed in the header",
"frame_info_list",
"=",
"[",
"]",
"frame_list",
"=",
... | Starts IPython embedded shell. This is similar to IPython.embed() but with some
additional features:
1. Print a list of the calling frames before entering the prompt
2. (optionally) copy local name space to global one to prevent certain IPython bug.
3. while doing so optinally overwrite names in the gl... | [
"Starts",
"IPython",
"embedded",
"shell",
".",
"This",
"is",
"similar",
"to",
"IPython",
".",
"embed",
"()",
"but",
"with",
"some",
"additional",
"features",
":"
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L148-L259 |
cknoll/ipydex | ipydex/core.py | ip_shell_after_exception | def ip_shell_after_exception(frame):
"""
Launches an IPython embedded shell in the namespace where an exception occurred.
:param frame:
:return:
"""
# let the user know, where this shell is 'waking up'
# construct frame list
# this will be printed in the header
frame_info_list = []... | python | def ip_shell_after_exception(frame):
"""
Launches an IPython embedded shell in the namespace where an exception occurred.
:param frame:
:return:
"""
# let the user know, where this shell is 'waking up'
# construct frame list
# this will be printed in the header
frame_info_list = []... | [
"def",
"ip_shell_after_exception",
"(",
"frame",
")",
":",
"# let the user know, where this shell is 'waking up'",
"# construct frame list",
"# this will be printed in the header",
"frame_info_list",
"=",
"[",
"]",
"frame_list",
"=",
"[",
"]",
"original_frame",
"=",
"frame",
... | Launches an IPython embedded shell in the namespace where an exception occurred.
:param frame:
:return: | [
"Launches",
"an",
"IPython",
"embedded",
"shell",
"in",
"the",
"namespace",
"where",
"an",
"exception",
"occurred",
"."
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L263-L324 |
cknoll/ipydex | ipydex/core.py | ips_excepthook | def ips_excepthook(excType, excValue, traceback, frame_upcount=0):
"""
This function is launched after an exception. It launches IPS in suitable frame.
Also note that if `__mu` is an integer in the local_ns of the closed IPS-Session then another Session
is launched in the corresponding frame: "__mu" mea... | python | def ips_excepthook(excType, excValue, traceback, frame_upcount=0):
"""
This function is launched after an exception. It launches IPS in suitable frame.
Also note that if `__mu` is an integer in the local_ns of the closed IPS-Session then another Session
is launched in the corresponding frame: "__mu" mea... | [
"def",
"ips_excepthook",
"(",
"excType",
",",
"excValue",
",",
"traceback",
",",
"frame_upcount",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"frame_upcount",
",",
"int",
")",
"# first: print the traceback:",
"tb_printer",
"=",
"TBPrinter",
"(",
"excType",
... | This function is launched after an exception. It launches IPS in suitable frame.
Also note that if `__mu` is an integer in the local_ns of the closed IPS-Session then another Session
is launched in the corresponding frame: "__mu" means = "move up" and referes to frame levels.
:param excType: Exception ... | [
"This",
"function",
"is",
"launched",
"after",
"an",
"exception",
".",
"It",
"launches",
"IPS",
"in",
"suitable",
"frame",
".",
"Also",
"note",
"that",
"if",
"__mu",
"is",
"an",
"integer",
"in",
"the",
"local_ns",
"of",
"the",
"closed",
"IPS",
"-",
"Sess... | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L327-L364 |
cknoll/ipydex | ipydex/core.py | color_exepthook | def color_exepthook(pdb=0, mode=2):
"""
Make tracebacks after exceptions colored, verbose, and/or call pdb
(python cmd line debugger) at the place where the exception occurs
"""
modus = ['Plain', 'Context', 'Verbose'][mode] # select the mode
sys.excepthook = ultratb.FormattedTB(mode=modus,
... | python | def color_exepthook(pdb=0, mode=2):
"""
Make tracebacks after exceptions colored, verbose, and/or call pdb
(python cmd line debugger) at the place where the exception occurs
"""
modus = ['Plain', 'Context', 'Verbose'][mode] # select the mode
sys.excepthook = ultratb.FormattedTB(mode=modus,
... | [
"def",
"color_exepthook",
"(",
"pdb",
"=",
"0",
",",
"mode",
"=",
"2",
")",
":",
"modus",
"=",
"[",
"'Plain'",
",",
"'Context'",
",",
"'Verbose'",
"]",
"[",
"mode",
"]",
"# select the mode",
"sys",
".",
"excepthook",
"=",
"ultratb",
".",
"FormattedTB",
... | Make tracebacks after exceptions colored, verbose, and/or call pdb
(python cmd line debugger) at the place where the exception occurs | [
"Make",
"tracebacks",
"after",
"exceptions",
"colored",
"verbose",
"and",
"/",
"or",
"call",
"pdb",
"(",
"python",
"cmd",
"line",
"debugger",
")",
"at",
"the",
"place",
"where",
"the",
"exception",
"occurs"
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L396-L405 |
cknoll/ipydex | ipydex/core.py | ip_extra_syshook | def ip_extra_syshook(fnc, pdb=0, filename=None):
"""
Extended system hook for exceptions.
supports logging of tracebacks to a file
lets fnc() be executed imediately before the IPython
Verbose Traceback is started
this can be used to pop up a QTMessageBox: "An exception occured"
"""
a... | python | def ip_extra_syshook(fnc, pdb=0, filename=None):
"""
Extended system hook for exceptions.
supports logging of tracebacks to a file
lets fnc() be executed imediately before the IPython
Verbose Traceback is started
this can be used to pop up a QTMessageBox: "An exception occured"
"""
a... | [
"def",
"ip_extra_syshook",
"(",
"fnc",
",",
"pdb",
"=",
"0",
",",
"filename",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"fnc",
",",
"collections",
".",
"Callable",
")",
"from",
"IPython",
".",
"core",
"import",
"ultratb",
"import",
"time",
"if"... | Extended system hook for exceptions.
supports logging of tracebacks to a file
lets fnc() be executed imediately before the IPython
Verbose Traceback is started
this can be used to pop up a QTMessageBox: "An exception occured" | [
"Extended",
"system",
"hook",
"for",
"exceptions",
"."
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L416-L455 |
cknoll/ipydex | ipydex/core.py | save_current_nb_as_html | def save_current_nb_as_html(info=False):
"""
Save the current notebook as html file in the same directory
"""
assert in_ipynb()
full_path = get_notebook_name()
path, filename = os.path.split(full_path)
wd_save = os.getcwd()
os.chdir(path)
cmd = 'jupyter nbconvert --to html "{}"'.fo... | python | def save_current_nb_as_html(info=False):
"""
Save the current notebook as html file in the same directory
"""
assert in_ipynb()
full_path = get_notebook_name()
path, filename = os.path.split(full_path)
wd_save = os.getcwd()
os.chdir(path)
cmd = 'jupyter nbconvert --to html "{}"'.fo... | [
"def",
"save_current_nb_as_html",
"(",
"info",
"=",
"False",
")",
":",
"assert",
"in_ipynb",
"(",
")",
"full_path",
"=",
"get_notebook_name",
"(",
")",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"full_path",
")",
"wd_save",
"=",
... | Save the current notebook as html file in the same directory | [
"Save",
"the",
"current",
"notebook",
"as",
"html",
"file",
"in",
"the",
"same",
"directory"
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L529-L547 |
cknoll/ipydex | ipydex/core.py | dirsearch | def dirsearch(word, obj, only_keys = True, deep = 0):
"""
search a string in dir(<some object>)
if object is a dict, then search in keys
optional arg only_keys: if False, returns also a str-version of
the attribute (or dict-value) instead only the key
this function is not c... | python | def dirsearch(word, obj, only_keys = True, deep = 0):
"""
search a string in dir(<some object>)
if object is a dict, then search in keys
optional arg only_keys: if False, returns also a str-version of
the attribute (or dict-value) instead only the key
this function is not c... | [
"def",
"dirsearch",
"(",
"word",
",",
"obj",
",",
"only_keys",
"=",
"True",
",",
"deep",
"=",
"0",
")",
":",
"word",
"=",
"word",
".",
"lower",
"(",
")",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"# only consider keys which are basestrings",... | search a string in dir(<some object>)
if object is a dict, then search in keys
optional arg only_keys: if False, returns also a str-version of
the attribute (or dict-value) instead only the key
this function is not case sensitive | [
"search",
"a",
"string",
"in",
"dir",
"(",
"<some",
"object",
">",
")",
"if",
"object",
"is",
"a",
"dict",
"then",
"search",
"in",
"keys"
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L557-L625 |
cknoll/ipydex | ipydex/core.py | get_whole_assignment_expression | def get_whole_assignment_expression(line, varname, seq_type):
"""
Example:
line = "x = Container(cargs=(a, b, c))"
varname = cargs
delimiter pair = "()"
return "a, b, c"
:return:
"""
tokens = list(tk.generate_tokens(io.StringIO(line).readline))
if issubclass(seq_type, tuple)... | python | def get_whole_assignment_expression(line, varname, seq_type):
"""
Example:
line = "x = Container(cargs=(a, b, c))"
varname = cargs
delimiter pair = "()"
return "a, b, c"
:return:
"""
tokens = list(tk.generate_tokens(io.StringIO(line).readline))
if issubclass(seq_type, tuple)... | [
"def",
"get_whole_assignment_expression",
"(",
"line",
",",
"varname",
",",
"seq_type",
")",
":",
"tokens",
"=",
"list",
"(",
"tk",
".",
"generate_tokens",
"(",
"io",
".",
"StringIO",
"(",
"line",
")",
".",
"readline",
")",
")",
"if",
"issubclass",
"(",
... | Example:
line = "x = Container(cargs=(a, b, c))"
varname = cargs
delimiter pair = "()"
return "a, b, c"
:return: | [
"Example",
":"
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L728-L794 |
cknoll/ipydex | ipydex/core.py | Container._get_attrs | def _get_attrs(self, names):
"""
Convenience function to extract multiple attributes at once
:param names: string of names separated by comma or space
:return:
"""
assert isinstance(names, str)
names = names.replace(",", " ").split(" ")
res = []
... | python | def _get_attrs(self, names):
"""
Convenience function to extract multiple attributes at once
:param names: string of names separated by comma or space
:return:
"""
assert isinstance(names, str)
names = names.replace(",", " ").split(" ")
res = []
... | [
"def",
"_get_attrs",
"(",
"self",
",",
"names",
")",
":",
"assert",
"isinstance",
"(",
"names",
",",
"str",
")",
"names",
"=",
"names",
".",
"replace",
"(",
"\",\"",
",",
"\" \"",
")",
".",
"split",
"(",
"\" \"",
")",
"res",
"=",
"[",
"]",
"for",
... | Convenience function to extract multiple attributes at once
:param names: string of names separated by comma or space
:return: | [
"Convenience",
"function",
"to",
"extract",
"multiple",
"attributes",
"at",
"once"
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L663-L679 |
cknoll/ipydex | ipydex/core.py | Container.fetch_locals | def fetch_locals(self, upcount=1):
"""
Magic function which fetches all variables from the callers namespace
:param upcount int, how many stack levels we go up
:return:
"""
frame = inspect.currentframe()
i = upcount
while True:
if frame.f_... | python | def fetch_locals(self, upcount=1):
"""
Magic function which fetches all variables from the callers namespace
:param upcount int, how many stack levels we go up
:return:
"""
frame = inspect.currentframe()
i = upcount
while True:
if frame.f_... | [
"def",
"fetch_locals",
"(",
"self",
",",
"upcount",
"=",
"1",
")",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"i",
"=",
"upcount",
"while",
"True",
":",
"if",
"frame",
".",
"f_back",
"is",
"None",
":",
"break",
"frame",
"=",
"frame"... | Magic function which fetches all variables from the callers namespace
:param upcount int, how many stack levels we go up
:return: | [
"Magic",
"function",
"which",
"fetches",
"all",
"variables",
"from",
"the",
"callers",
"namespace",
":",
"param",
"upcount",
"int",
"how",
"many",
"stack",
"levels",
"we",
"go",
"up",
":",
"return",
":"
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L681-L699 |
cknoll/ipydex | ipydex/core.py | Container.publish_attrs | def publish_attrs(self, upcount=1):
"""
Magic function which inject all attrs into the callers namespace
:param upcount int, how many stack levels we go up
:return:
"""
frame = inspect.currentframe()
i = upcount
while True:
if frame.f_back... | python | def publish_attrs(self, upcount=1):
"""
Magic function which inject all attrs into the callers namespace
:param upcount int, how many stack levels we go up
:return:
"""
frame = inspect.currentframe()
i = upcount
while True:
if frame.f_back... | [
"def",
"publish_attrs",
"(",
"self",
",",
"upcount",
"=",
"1",
")",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"i",
"=",
"upcount",
"while",
"True",
":",
"if",
"frame",
".",
"f_back",
"is",
"None",
":",
"break",
"frame",
"=",
"frame... | Magic function which inject all attrs into the callers namespace
:param upcount int, how many stack levels we go up
:return: | [
"Magic",
"function",
"which",
"inject",
"all",
"attrs",
"into",
"the",
"callers",
"namespace",
":",
"param",
"upcount",
"int",
"how",
"many",
"stack",
"levels",
"we",
"go",
"up",
":",
"return",
":"
] | train | https://github.com/cknoll/ipydex/blob/ca528ce4c97ee934e48efbd5983c1b7cd88bec9d/ipydex/core.py#L701-L719 |
ionelmc/python-cogen | examples/cogen-irc/CogenIrcApp/cogenircapp/controllers/irc.py | parsemsg | def parsemsg(s): # stolen from twisted.words
"""Breaks a message from an IRC server into its prefix, command, and arguments.
"""
prefix = ''
trailing = []
if not s:
raise Exception("Empty line.")
if s[0] == ':':
prefix, s = s[1:].split(' ', 1)
if s.find(' :') != -1:
... | python | def parsemsg(s): # stolen from twisted.words
"""Breaks a message from an IRC server into its prefix, command, and arguments.
"""
prefix = ''
trailing = []
if not s:
raise Exception("Empty line.")
if s[0] == ':':
prefix, s = s[1:].split(' ', 1)
if s.find(' :') != -1:
... | [
"def",
"parsemsg",
"(",
"s",
")",
":",
"# stolen from twisted.words\r",
"prefix",
"=",
"''",
"trailing",
"=",
"[",
"]",
"if",
"not",
"s",
":",
"raise",
"Exception",
"(",
"\"Empty line.\"",
")",
"if",
"s",
"[",
"0",
"]",
"==",
"':'",
":",
"prefix",
",",... | Breaks a message from an IRC server into its prefix, command, and arguments. | [
"Breaks",
"a",
"message",
"from",
"an",
"IRC",
"server",
"into",
"its",
"prefix",
"command",
"and",
"arguments",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/cogen-irc/CogenIrcApp/cogenircapp/controllers/irc.py#L25-L41 |
ionelmc/python-cogen | examples/cogen-irc/CogenIrcApp/cogenircapp/controllers/irc.py | Connection.pull | def pull(self):
"""This coroutine handles the server connection, does a basic parse on
the received messages and put them in a queue named events.
The controllers pull method will take the messages from that queue.
"""
self.sock = sockets.Socket()
self.sock.settimeo... | python | def pull(self):
"""This coroutine handles the server connection, does a basic parse on
the received messages and put them in a queue named events.
The controllers pull method will take the messages from that queue.
"""
self.sock = sockets.Socket()
self.sock.settimeo... | [
"def",
"pull",
"(",
"self",
")",
":",
"self",
".",
"sock",
"=",
"sockets",
".",
"Socket",
"(",
")",
"self",
".",
"sock",
".",
"settimeout",
"(",
"self",
".",
"sock_timo",
")",
"yield",
"events",
".",
"AddCoro",
"(",
"self",
".",
"monitor",
")",
"wh... | This coroutine handles the server connection, does a basic parse on
the received messages and put them in a queue named events.
The controllers pull method will take the messages from that queue. | [
"This",
"coroutine",
"handles",
"the",
"server",
"connection",
"does",
"a",
"basic",
"parse",
"on",
"the",
"received",
"messages",
"and",
"put",
"them",
"in",
"a",
"queue",
"named",
"events",
".",
"The",
"controllers",
"pull",
"method",
"will",
"take",
"the"... | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/cogen-irc/CogenIrcApp/cogenircapp/controllers/irc.py#L53-L87 |
ionelmc/python-cogen | examples/cogen-irc/CogenIrcApp/cogenircapp/controllers/irc.py | IrcController.push | def push(self, id):
"Sends a message to the specified connection (id)"
conn = session['connections'].get(id, None)
if conn:
msgs = simplejson.loads(request.body)
for msg in msgs:
try:
cmd = msg.pop(0).upper()
... | python | def push(self, id):
"Sends a message to the specified connection (id)"
conn = session['connections'].get(id, None)
if conn:
msgs = simplejson.loads(request.body)
for msg in msgs:
try:
cmd = msg.pop(0).upper()
... | [
"def",
"push",
"(",
"self",
",",
"id",
")",
":",
"conn",
"=",
"session",
"[",
"'connections'",
"]",
".",
"get",
"(",
"id",
",",
"None",
")",
"if",
"conn",
":",
"msgs",
"=",
"simplejson",
".",
"loads",
"(",
"request",
".",
"body",
")",
"for",
"msg... | Sends a message to the specified connection (id) | [
"Sends",
"a",
"message",
"to",
"the",
"specified",
"connection",
"(",
"id",
")"
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/cogen-irc/CogenIrcApp/cogenircapp/controllers/irc.py#L108-L138 |
ionelmc/python-cogen | examples/cogen-irc/CogenIrcApp/cogenircapp/controllers/irc.py | IrcController.connect | def connect(self, server):
"Connects to a server and return a connection id."
if 'connections' not in session:
session['connections'] = {}
session.save()
conns = session['connections']
id = str(len(conns))
conn = Connection(server)
conns[... | python | def connect(self, server):
"Connects to a server and return a connection id."
if 'connections' not in session:
session['connections'] = {}
session.save()
conns = session['connections']
id = str(len(conns))
conn = Connection(server)
conns[... | [
"def",
"connect",
"(",
"self",
",",
"server",
")",
":",
"if",
"'connections'",
"not",
"in",
"session",
":",
"session",
"[",
"'connections'",
"]",
"=",
"{",
"}",
"session",
".",
"save",
"(",
")",
"conns",
"=",
"session",
"[",
"'connections'",
"]",
"id",... | Connects to a server and return a connection id. | [
"Connects",
"to",
"a",
"server",
"and",
"return",
"a",
"connection",
"id",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/cogen-irc/CogenIrcApp/cogenircapp/controllers/irc.py#L140-L151 |
ionelmc/python-cogen | examples/cogen-irc/CogenIrcApp/cogenircapp/controllers/irc.py | IrcController.pull | def pull(self, id):
"""Take the messages from the queue and if there are none wait 30
seconds till returning an empty message.
Also, cogen's wsgi async extensions are in the environ and prefixed with
'cogen.'
"""
conn = session['connections'].get(id, None)
... | python | def pull(self, id):
"""Take the messages from the queue and if there are none wait 30
seconds till returning an empty message.
Also, cogen's wsgi async extensions are in the environ and prefixed with
'cogen.'
"""
conn = session['connections'].get(id, None)
... | [
"def",
"pull",
"(",
"self",
",",
"id",
")",
":",
"conn",
"=",
"session",
"[",
"'connections'",
"]",
".",
"get",
"(",
"id",
",",
"None",
")",
"conn",
".",
"last_update",
"=",
"time",
".",
"time",
"(",
")",
"if",
"conn",
":",
"ev_list",
"=",
"[",
... | Take the messages from the queue and if there are none wait 30
seconds till returning an empty message.
Also, cogen's wsgi async extensions are in the environ and prefixed with
'cogen.' | [
"Take",
"the",
"messages",
"from",
"the",
"queue",
"and",
"if",
"there",
"are",
"none",
"wait",
"30",
"seconds",
"till",
"returning",
"an",
"empty",
"message",
".",
"Also",
"cogen",
"s",
"wsgi",
"async",
"extensions",
"are",
"in",
"the",
"environ",
"and",
... | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/examples/cogen-irc/CogenIrcApp/cogenircapp/controllers/irc.py#L153-L196 |
cgearhart/Resound | extract.py | main | def main(input_filename, songname, format, counter):
"""
Calculate the fingerprint hashses of the referenced audio file and save
to disk as a pickle file
"""
# open the file & convert to wav
song_data = AudioSegment.from_file(input_filename, format=format)
song_data = song_data.set_channels... | python | def main(input_filename, songname, format, counter):
"""
Calculate the fingerprint hashses of the referenced audio file and save
to disk as a pickle file
"""
# open the file & convert to wav
song_data = AudioSegment.from_file(input_filename, format=format)
song_data = song_data.set_channels... | [
"def",
"main",
"(",
"input_filename",
",",
"songname",
",",
"format",
",",
"counter",
")",
":",
"# open the file & convert to wav",
"song_data",
"=",
"AudioSegment",
".",
"from_file",
"(",
"input_filename",
",",
"format",
"=",
"format",
")",
"song_data",
"=",
"s... | Calculate the fingerprint hashses of the referenced audio file and save
to disk as a pickle file | [
"Calculate",
"the",
"fingerprint",
"hashses",
"of",
"the",
"referenced",
"audio",
"file",
"and",
"save",
"to",
"disk",
"as",
"a",
"pickle",
"file"
] | train | https://github.com/cgearhart/Resound/blob/83a15be0ce2dc13003574c6039f8a1ad87734bc2/extract.py#L16-L42 |
shimpe/pyvectortween | vectortween/PointAnimation.py | PointAnimation.make_frame | def make_frame(self, frame, birthframe, startframe, stopframe, deathframe, noiseframe=None):
"""
:param frame: current frame
:param birthframe: frame where this animation starts returning something other than None
:param startframe: frame where animation starts to evolve
:param ... | python | def make_frame(self, frame, birthframe, startframe, stopframe, deathframe, noiseframe=None):
"""
:param frame: current frame
:param birthframe: frame where this animation starts returning something other than None
:param startframe: frame where animation starts to evolve
:param ... | [
"def",
"make_frame",
"(",
"self",
",",
"frame",
",",
"birthframe",
",",
"startframe",
",",
"stopframe",
",",
"deathframe",
",",
"noiseframe",
"=",
"None",
")",
":",
"newx",
"=",
"self",
".",
"anim_x",
".",
"make_frame",
"(",
"frame",
",",
"birthframe",
"... | :param frame: current frame
:param birthframe: frame where this animation starts returning something other than None
:param startframe: frame where animation starts to evolve
:param stopframe: frame where animation is completed
:param deathframe: frame where animation starts to return N... | [
":",
"param",
"frame",
":",
"current",
"frame",
":",
"param",
"birthframe",
":",
"frame",
"where",
"this",
"animation",
"starts",
"returning",
"something",
"other",
"than",
"None",
":",
"param",
"startframe",
":",
"frame",
"where",
"animation",
"starts",
"to",... | train | https://github.com/shimpe/pyvectortween/blob/aff071180474739060ec2d3102c39c8e73510988/vectortween/PointAnimation.py#L32-L52 |
seibert-media/Highton | highton/parsing/xml_decoder.py | XMLDecoder.decode | def decode(cls, root_element):
"""
Decode the object to the object
:param root_element: the parsed xml Element
:type root_element: xml.etree.ElementTree.Element
:return: the decoded Element as object
:rtype: object
"""
new_object = cls()
field_nam... | python | def decode(cls, root_element):
"""
Decode the object to the object
:param root_element: the parsed xml Element
:type root_element: xml.etree.ElementTree.Element
:return: the decoded Element as object
:rtype: object
"""
new_object = cls()
field_nam... | [
"def",
"decode",
"(",
"cls",
",",
"root_element",
")",
":",
"new_object",
"=",
"cls",
"(",
")",
"field_names_to_attributes",
"=",
"new_object",
".",
"_get_field_names_to_attributes",
"(",
")",
"for",
"child_element",
"in",
"root_element",
":",
"new_object",
".",
... | Decode the object to the object
:param root_element: the parsed xml Element
:type root_element: xml.etree.ElementTree.Element
:return: the decoded Element as object
:rtype: object | [
"Decode",
"the",
"object",
"to",
"the",
"object"
] | train | https://github.com/seibert-media/Highton/blob/1519e4fb105f62882c2e7bc81065d994649558d8/highton/parsing/xml_decoder.py#L62-L75 |
justquick/django-native-tags | native_tags/contrib/cal.py | calendar | def calendar(format, *args, **kwargs):
"""
Creates a formatted ``HTMLCalendar``.
Argument ``format`` can be one of ``month``, ``year``, or ``yearpage``
Keyword arguments are collected and passed into ``HTMLCalendar.formatmonth``,
``HTMLCalendar.formatyear``, and ``HTMLCalendar.formatyearpage``
... | python | def calendar(format, *args, **kwargs):
"""
Creates a formatted ``HTMLCalendar``.
Argument ``format`` can be one of ``month``, ``year``, or ``yearpage``
Keyword arguments are collected and passed into ``HTMLCalendar.formatmonth``,
``HTMLCalendar.formatyear``, and ``HTMLCalendar.formatyearpage``
... | [
"def",
"calendar",
"(",
"format",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cal",
"=",
"HTMLCalendar",
"(",
"kwargs",
".",
"pop",
"(",
"'firstweekday'",
",",
"0",
")",
")",
"return",
"getattr",
"(",
"cal",
",",
"'format%s'",
"%",
"format"... | Creates a formatted ``HTMLCalendar``.
Argument ``format`` can be one of ``month``, ``year``, or ``yearpage``
Keyword arguments are collected and passed into ``HTMLCalendar.formatmonth``,
``HTMLCalendar.formatyear``, and ``HTMLCalendar.formatyearpage``
Syntax::
{% cale... | [
"Creates",
"a",
"formatted",
"HTMLCalendar",
".",
"Argument",
"format",
"can",
"be",
"one",
"of",
"month",
"year",
"or",
"yearpage",
"Keyword",
"arguments",
"are",
"collected",
"and",
"passed",
"into",
"HTMLCalendar",
".",
"formatmonth",
"HTMLCalendar",
".",
"fo... | train | https://github.com/justquick/django-native-tags/blob/d40b976ee1cb13faeb04f0dedf02933d4274abf2/native_tags/contrib/cal.py#L4-L22 |
gregmccoy/melissadata | melissadata/melissadata.py | Personator.verify_address | def verify_address(self, addr1="", addr2="", city="", fname="", lname="", phone="", province="", postal="", country="", email="", recordID="", freeform= ""):
"""verify_address
Builds a JSON request to send to Melissa data. Takes in all needed address info.
Args:
addr1 (str):Con... | python | def verify_address(self, addr1="", addr2="", city="", fname="", lname="", phone="", province="", postal="", country="", email="", recordID="", freeform= ""):
"""verify_address
Builds a JSON request to send to Melissa data. Takes in all needed address info.
Args:
addr1 (str):Con... | [
"def",
"verify_address",
"(",
"self",
",",
"addr1",
"=",
"\"\"",
",",
"addr2",
"=",
"\"\"",
",",
"city",
"=",
"\"\"",
",",
"fname",
"=",
"\"\"",
",",
"lname",
"=",
"\"\"",
",",
"phone",
"=",
"\"\"",
",",
"province",
"=",
"\"\"",
",",
"postal",
"=",... | verify_address
Builds a JSON request to send to Melissa data. Takes in all needed address info.
Args:
addr1 (str):Contains info for Melissa data
addr2 (str):Contains info for Melissa data
city (str):Contains info for Melissa data
fname (s... | [
"verify_address"
] | train | https://github.com/gregmccoy/melissadata/blob/e610152c8ec98f673b9c7be4d359bfacdfde7c1e/melissadata/melissadata.py#L30-L79 |
gregmccoy/melissadata | melissadata/melissadata.py | Personator.parse_results | def parse_results(self, data):
"""parse_results
Parses the MelissaData response.
Args:
data (dict): Contains MelissaData response
Returns:
results, either contains a dict with corrected address info or -1 for an invalid address.
"""
resu... | python | def parse_results(self, data):
"""parse_results
Parses the MelissaData response.
Args:
data (dict): Contains MelissaData response
Returns:
results, either contains a dict with corrected address info or -1 for an invalid address.
"""
resu... | [
"def",
"parse_results",
"(",
"self",
",",
"data",
")",
":",
"results",
"=",
"[",
"]",
"if",
"len",
"(",
"data",
"[",
"\"Records\"",
"]",
")",
"<",
"1",
":",
"return",
"-",
"1",
"codes",
"=",
"data",
"[",
"\"Records\"",
"]",
"[",
"0",
"]",
"[",
... | parse_results
Parses the MelissaData response.
Args:
data (dict): Contains MelissaData response
Returns:
results, either contains a dict with corrected address info or -1 for an invalid address. | [
"parse_results"
] | train | https://github.com/gregmccoy/melissadata/blob/e610152c8ec98f673b9c7be4d359bfacdfde7c1e/melissadata/melissadata.py#L81-L108 |
ionelmc/python-cogen | cogen/core/schedulers.py | Scheduler.add | def add(self, coro, args=(), kwargs={}, first=True):
"""Add a coroutine in the scheduler. You can add arguments
(_args_, _kwargs_) to init the coroutine with."""
assert callable(coro), "'%s' not a callable object" % coro
coro = coro(*args, **kwargs)
if first:
se... | python | def add(self, coro, args=(), kwargs={}, first=True):
"""Add a coroutine in the scheduler. You can add arguments
(_args_, _kwargs_) to init the coroutine with."""
assert callable(coro), "'%s' not a callable object" % coro
coro = coro(*args, **kwargs)
if first:
se... | [
"def",
"add",
"(",
"self",
",",
"coro",
",",
"args",
"=",
"(",
")",
",",
"kwargs",
"=",
"{",
"}",
",",
"first",
"=",
"True",
")",
":",
"assert",
"callable",
"(",
"coro",
")",
",",
"\"'%s' not a callable object\"",
"%",
"coro",
"coro",
"=",
"coro",
... | Add a coroutine in the scheduler. You can add arguments
(_args_, _kwargs_) to init the coroutine with. | [
"Add",
"a",
"coroutine",
"in",
"the",
"scheduler",
".",
"You",
"can",
"add",
"arguments",
"(",
"_args_",
"_kwargs_",
")",
"to",
"init",
"the",
"coroutine",
"with",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/schedulers.py#L89-L98 |
ionelmc/python-cogen | cogen/core/schedulers.py | Scheduler.next_timer_delta | def next_timer_delta(self):
"Returns a timevalue that the proactor will wait on."
if self.timeouts and not self.active:
now = getnow()
timo = self.timeouts[0].timeout
if now >= timo:
#looks like we've exceded the time
return 0
... | python | def next_timer_delta(self):
"Returns a timevalue that the proactor will wait on."
if self.timeouts and not self.active:
now = getnow()
timo = self.timeouts[0].timeout
if now >= timo:
#looks like we've exceded the time
return 0
... | [
"def",
"next_timer_delta",
"(",
"self",
")",
":",
"if",
"self",
".",
"timeouts",
"and",
"not",
"self",
".",
"active",
":",
"now",
"=",
"getnow",
"(",
")",
"timo",
"=",
"self",
".",
"timeouts",
"[",
"0",
"]",
".",
"timeout",
"if",
"now",
">=",
"timo... | Returns a timevalue that the proactor will wait on. | [
"Returns",
"a",
"timevalue",
"that",
"the",
"proactor",
"will",
"wait",
"on",
"."
] | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/schedulers.py#L100-L114 |
ionelmc/python-cogen | cogen/core/schedulers.py | Scheduler.handle_timeouts | def handle_timeouts(self):
"""Handle timeouts. Raise timeouted operations with a OperationTimeout
in the associated coroutine (if they are still alive and the operation
hasn't actualy sucessfuly completed) or, if the operation has a
weak_timeout flag, update the timeout point and add... | python | def handle_timeouts(self):
"""Handle timeouts. Raise timeouted operations with a OperationTimeout
in the associated coroutine (if they are still alive and the operation
hasn't actualy sucessfuly completed) or, if the operation has a
weak_timeout flag, update the timeout point and add... | [
"def",
"handle_timeouts",
"(",
"self",
")",
":",
"now",
"=",
"getnow",
"(",
")",
"#~ print '>to:', self.timeouts, self.timeouts and self.timeouts[0].timeout <= now\r",
"while",
"self",
".",
"timeouts",
"and",
"self",
".",
"timeouts",
"[",
"0",
"]",
".",
"timeout",
"... | Handle timeouts. Raise timeouted operations with a OperationTimeout
in the associated coroutine (if they are still alive and the operation
hasn't actualy sucessfuly completed) or, if the operation has a
weak_timeout flag, update the timeout point and add it back in the
heapq.
... | [
"Handle",
"timeouts",
".",
"Raise",
"timeouted",
"operations",
"with",
"a",
"OperationTimeout",
"in",
"the",
"associated",
"coroutine",
"(",
"if",
"they",
"are",
"still",
"alive",
"and",
"the",
"operation",
"hasn",
"t",
"actualy",
"sucessfuly",
"completed",
")",... | train | https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/schedulers.py#L116-L160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.