repo stringlengths 7 55 | path stringlengths 4 223 | url stringlengths 87 315 | code stringlengths 75 104k | code_tokens list | docstring stringlengths 1 46.9k | docstring_tokens list | language stringclasses 1
value | partition stringclasses 3
values | avg_line_len float64 7.91 980 |
|---|---|---|---|---|---|---|---|---|---|
bprinty/gems | gems/datatypes.py | https://github.com/bprinty/gems/blob/3ff76407af0e71621dada744cd964611e998699c/gems/datatypes.py#L466-L486 | def json(self):
"""
Return JSON representation of object.
"""
if self.meta_type == 'list':
ret = []
for dat in self._list:
if not isinstance(dat, composite):
ret.append(dat)
else:
ret.append(d... | [
"def",
"json",
"(",
"self",
")",
":",
"if",
"self",
".",
"meta_type",
"==",
"'list'",
":",
"ret",
"=",
"[",
"]",
"for",
"dat",
"in",
"self",
".",
"_list",
":",
"if",
"not",
"isinstance",
"(",
"dat",
",",
"composite",
")",
":",
"ret",
".",
"append... | Return JSON representation of object. | [
"Return",
"JSON",
"representation",
"of",
"object",
"."
] | python | valid | 30.380952 |
slickqa/python-client | slickqa/micromodels/packages/PySO8601/datetimestamps.py | https://github.com/slickqa/python-client/blob/1d36b4977cd4140d7d24917cab2b3f82b60739c2/slickqa/micromodels/packages/PySO8601/datetimestamps.py#L91-L120 | def parse_date(datestring):
"""Attepmts to parse an ISO8601 formatted ``datestring``.
Returns a ``datetime.datetime`` object.
"""
datestring = str(datestring).strip()
if not datestring[0].isdigit():
raise ParseError()
if 'W' in datestring.upper():
try:
datestring =... | [
"def",
"parse_date",
"(",
"datestring",
")",
":",
"datestring",
"=",
"str",
"(",
"datestring",
")",
".",
"strip",
"(",
")",
"if",
"not",
"datestring",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
":",
"raise",
"ParseError",
"(",
")",
"if",
"'W'",
"in",
... | Attepmts to parse an ISO8601 formatted ``datestring``.
Returns a ``datetime.datetime`` object. | [
"Attepmts",
"to",
"parse",
"an",
"ISO8601",
"formatted",
"datestring",
"."
] | python | train | 30.8 |
amanusk/s-tui | s_tui/s_tui.py | https://github.com/amanusk/s-tui/blob/5e89d15081e716024db28ec03b1e3a7710330951/s_tui/s_tui.py#L455-L463 | def _generate_cpu_stats():
"""Read and display processor name """
cpu_name = urwid.Text("CPU Name N/A", align="center")
try:
cpu_name = urwid.Text(get_processor_name().strip(), align="center")
except OSError:
logging.info("CPU name not available")
return [... | [
"def",
"_generate_cpu_stats",
"(",
")",
":",
"cpu_name",
"=",
"urwid",
".",
"Text",
"(",
"\"CPU Name N/A\"",
",",
"align",
"=",
"\"center\"",
")",
"try",
":",
"cpu_name",
"=",
"urwid",
".",
"Text",
"(",
"get_processor_name",
"(",
")",
".",
"strip",
"(",
... | Read and display processor name | [
"Read",
"and",
"display",
"processor",
"name"
] | python | train | 47.111111 |
tech-pi/doufo | src/python/doufo/tensor/vector.py | https://github.com/tech-pi/doufo/blob/3d375fef30670597768a6eef809b75b4b1b5a3fd/src/python/doufo/tensor/vector.py#L34-L41 | def one_hot(cls, n, l):
"""
n: position of "hot"
l: lenght of vector
"""
v = [0.0] * l
v[n] = 1.0
return Vector(v) | [
"def",
"one_hot",
"(",
"cls",
",",
"n",
",",
"l",
")",
":",
"v",
"=",
"[",
"0.0",
"]",
"*",
"l",
"v",
"[",
"n",
"]",
"=",
"1.0",
"return",
"Vector",
"(",
"v",
")"
] | n: position of "hot"
l: lenght of vector | [
"n",
":",
"position",
"of",
"hot",
"l",
":",
"lenght",
"of",
"vector"
] | python | train | 20.375 |
gem/oq-engine | openquake/hazardlib/gsim/campbell_bozorgnia_2008.py | https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/campbell_bozorgnia_2008.py#L340-L354 | def _compute_intra_event_alpha(self, C, vs30, pga1100):
"""
Returns the linearised functional relationship between fsite and
pga1100, determined from the partial derivative defined on equation 17
on page 148
"""
alpha = np.zeros_like(vs30, dtype=float)
idx = vs30 ... | [
"def",
"_compute_intra_event_alpha",
"(",
"self",
",",
"C",
",",
"vs30",
",",
"pga1100",
")",
":",
"alpha",
"=",
"np",
".",
"zeros_like",
"(",
"vs30",
",",
"dtype",
"=",
"float",
")",
"idx",
"=",
"vs30",
"<",
"C",
"[",
"'k1'",
"]",
"if",
"np",
".",... | Returns the linearised functional relationship between fsite and
pga1100, determined from the partial derivative defined on equation 17
on page 148 | [
"Returns",
"the",
"linearised",
"functional",
"relationship",
"between",
"fsite",
"and",
"pga1100",
"determined",
"from",
"the",
"partial",
"derivative",
"defined",
"on",
"equation",
"17",
"on",
"page",
"148"
] | python | train | 38.933333 |
google/grr | grr/server/grr_response_server/maintenance_utils.py | https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/maintenance_utils.py#L86-L133 | def RotateServerKey(cn=u"grr", keylength=4096):
"""This function creates and installs a new server key.
Note that
- Clients might experience intermittent connection problems after
the server keys rotated.
- It's not possible to go back to an earlier key. Clients that see a
new certificate will rememb... | [
"def",
"RotateServerKey",
"(",
"cn",
"=",
"u\"grr\"",
",",
"keylength",
"=",
"4096",
")",
":",
"ca_certificate",
"=",
"config",
".",
"CONFIG",
"[",
"\"CA.certificate\"",
"]",
"ca_private_key",
"=",
"config",
".",
"CONFIG",
"[",
"\"PrivateKeys.ca_key\"",
"]",
"... | This function creates and installs a new server key.
Note that
- Clients might experience intermittent connection problems after
the server keys rotated.
- It's not possible to go back to an earlier key. Clients that see a
new certificate will remember the cert's serial number and refuse
to accept ... | [
"This",
"function",
"creates",
"and",
"installs",
"a",
"new",
"server",
"key",
"."
] | python | train | 33.979167 |
Azure/azure-uamqp-python | uamqp/authentication/cbs_auth.py | https://github.com/Azure/azure-uamqp-python/blob/b67e4fcaf2e8a337636947523570239c10a58ae2/uamqp/authentication/cbs_auth.py#L243-L256 | def update_token(self):
"""If a username and password are present - attempt to use them to
request a fresh SAS token.
"""
if not self.username or not self.password:
raise errors.TokenExpired("Unable to refresh token - no username or password.")
encoded_uri = compat.qu... | [
"def",
"update_token",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"username",
"or",
"not",
"self",
".",
"password",
":",
"raise",
"errors",
".",
"TokenExpired",
"(",
"\"Unable to refresh token - no username or password.\"",
")",
"encoded_uri",
"=",
"compat",... | If a username and password are present - attempt to use them to
request a fresh SAS token. | [
"If",
"a",
"username",
"and",
"password",
"are",
"present",
"-",
"attempt",
"to",
"use",
"them",
"to",
"request",
"a",
"fresh",
"SAS",
"token",
"."
] | python | train | 51.571429 |
vertexproject/synapse | synapse/lib/scope.py | https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/scope.py#L80-L87 | def add(self, name, *vals):
'''
Add values as iter() compatible items in the current scope frame.
'''
item = self.frames[-1].get(name)
if item is None:
self.frames[-1][name] = item = []
item.extend(vals) | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"*",
"vals",
")",
":",
"item",
"=",
"self",
".",
"frames",
"[",
"-",
"1",
"]",
".",
"get",
"(",
"name",
")",
"if",
"item",
"is",
"None",
":",
"self",
".",
"frames",
"[",
"-",
"1",
"]",
"[",
"name... | Add values as iter() compatible items in the current scope frame. | [
"Add",
"values",
"as",
"iter",
"()",
"compatible",
"items",
"in",
"the",
"current",
"scope",
"frame",
"."
] | python | train | 32 |
google/grumpy | third_party/pypy/_sha.py | https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/_sha.py#L64-L81 | def _bytelist2longBigEndian(list):
"Transform a list of characters into a list of longs."
imax = len(list) // 4
hl = [0] * imax
j = 0
i = 0
while i < imax:
b0 = ord(list[j]) << 24
b1 = ord(list[j+1]) << 16
b2 = ord(list[j+2]) << 8
b3 = ord(list[j+3])
hl[... | [
"def",
"_bytelist2longBigEndian",
"(",
"list",
")",
":",
"imax",
"=",
"len",
"(",
"list",
")",
"//",
"4",
"hl",
"=",
"[",
"0",
"]",
"*",
"imax",
"j",
"=",
"0",
"i",
"=",
"0",
"while",
"i",
"<",
"imax",
":",
"b0",
"=",
"ord",
"(",
"list",
"[",... | Transform a list of characters into a list of longs. | [
"Transform",
"a",
"list",
"of",
"characters",
"into",
"a",
"list",
"of",
"longs",
"."
] | python | valid | 20.666667 |
optimizely/optimizely-client-python | optimizely/client.py | https://github.com/optimizely/optimizely-client-python/blob/c4a121e8ac66e44f6ef4ad4959ef46ed3992708a/optimizely/client.py#L77-L99 | def parse_response(resp):
""" Method to parse response from the Optimizely API and
return results as JSON. Errors are thrown for various
errors that the API can throw.
"""
if resp.status_code in [200, 201, 202]:
return resp.json()
elif resp.status_code == 204:... | [
"def",
"parse_response",
"(",
"resp",
")",
":",
"if",
"resp",
".",
"status_code",
"in",
"[",
"200",
",",
"201",
",",
"202",
"]",
":",
"return",
"resp",
".",
"json",
"(",
")",
"elif",
"resp",
".",
"status_code",
"==",
"204",
":",
"return",
"None",
"... | Method to parse response from the Optimizely API and
return results as JSON. Errors are thrown for various
errors that the API can throw. | [
"Method",
"to",
"parse",
"response",
"from",
"the",
"Optimizely",
"API",
"and",
"return",
"results",
"as",
"JSON",
".",
"Errors",
"are",
"thrown",
"for",
"various",
"errors",
"that",
"the",
"API",
"can",
"throw",
"."
] | python | train | 40.565217 |
StackStorm/pybind | pybind/slxos/v17s_1_02/interface_vlan/vlan/ip/igmpVlan/snooping/igmps_mrouter/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/interface_vlan/vlan/ip/igmpVlan/snooping/igmps_mrouter/__init__.py#L92-L113 | def _set_igmps_interface(self, v, load=False):
"""
Setter method for igmps_interface, mapped from YANG variable /interface_vlan/vlan/ip/igmpVlan/snooping/igmps_mrouter/igmps_interface (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_igmps_interface is considered as... | [
"def",
"_set_igmps_interface",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
... | Setter method for igmps_interface, mapped from YANG variable /interface_vlan/vlan/ip/igmpVlan/snooping/igmps_mrouter/igmps_interface (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_igmps_interface is considered as a private
method. Backends looking to populate this va... | [
"Setter",
"method",
"for",
"igmps_interface",
"mapped",
"from",
"YANG",
"variable",
"/",
"interface_vlan",
"/",
"vlan",
"/",
"ip",
"/",
"igmpVlan",
"/",
"snooping",
"/",
"igmps_mrouter",
"/",
"igmps_interface",
"(",
"list",
")",
"If",
"this",
"variable",
"is",... | python | train | 115.863636 |
OzymandiasTheGreat/python-libinput | libinput/event.py | https://github.com/OzymandiasTheGreat/python-libinput/blob/1f477ee9f1d56b284b20e0317ea8967c64ef1218/libinput/event.py#L626-L647 | def coords(self):
"""The current absolute coordinates of the touch event,
in mm from the top left corner of the device.
To get the corresponding output screen coordinates, use
:meth:`transform_coords`.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventT... | [
"def",
"coords",
"(",
"self",
")",
":",
"if",
"self",
".",
"type",
"not",
"in",
"{",
"EventType",
".",
"TOUCH_DOWN",
",",
"EventType",
".",
"TOUCH_MOTION",
"}",
":",
"raise",
"AttributeError",
"(",
"_wrong_prop",
".",
"format",
"(",
"self",
".",
"type",
... | The current absolute coordinates of the touch event,
in mm from the top left corner of the device.
To get the corresponding output screen coordinates, use
:meth:`transform_coords`.
For events not of type :attr:`~libinput.constant.EventType.TOUCH_DOWN`,
:attr:`~libinput.constant.EventType.TOUCH_MOTION`, this... | [
"The",
"current",
"absolute",
"coordinates",
"of",
"the",
"touch",
"event",
"in",
"mm",
"from",
"the",
"top",
"left",
"corner",
"of",
"the",
"device",
"."
] | python | train | 33.318182 |
mar10/pyftpsync | ftpsync/resources.py | https://github.com/mar10/pyftpsync/blob/bbdc94186975cdc1cc4f678474bdce08bce7bb76/ftpsync/resources.py#L126-L140 | def override_operation(self, operation, reason):
"""Re-Classify entry pair."""
prev_class = (self.local_classification, self.remote_classification)
prev_op = self.operation
assert operation != prev_op
assert operation in PAIR_OPERATIONS
if self.any_entry.target.synchroniz... | [
"def",
"override_operation",
"(",
"self",
",",
"operation",
",",
"reason",
")",
":",
"prev_class",
"=",
"(",
"self",
".",
"local_classification",
",",
"self",
".",
"remote_classification",
")",
"prev_op",
"=",
"self",
".",
"operation",
"assert",
"operation",
"... | Re-Classify entry pair. | [
"Re",
"-",
"Classify",
"entry",
"pair",
"."
] | python | train | 39.8 |
JukeboxPipeline/jukebox-core | src/jukeboxcore/gui/filesysitemdata.py | https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/filesysitemdata.py#L27-L40 | def taskfileinfo_task_data(tfi, role):
"""Return the data for task
:param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the task
:rtype:... | [
"def",
"taskfileinfo_task_data",
"(",
"tfi",
",",
"role",
")",
":",
"task",
"=",
"tfi",
".",
"task",
"if",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"DisplayRole",
"or",
"role",
"==",
"QtCore",
".",
"Qt",
".",
"EditRole",
":",
"return",
"task",
".",
"n... | Return the data for task
:param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the task
:rtype: depending on role
:raises: None | [
"Return",
"the",
"data",
"for",
"task"
] | python | train | 33.142857 |
empirical-org/Quill-NLP-Tools-and-Datasets | genmodel/manager.py | https://github.com/empirical-org/Quill-NLP-Tools-and-Datasets/blob/f2ff579ddf3a556d9cdc47c5f702422fa06863d9/genmodel/manager.py#L413-L453 | def training_data(job_id):
'''Returns training_examples for a given job_id from offset to limit
If full_info parameter is greater than 0, will return extra architecture
info,
GET /jobs/139/vectors?offset=0&limit=10&full_info=1
{
"labeled_vectors": [{"vector":{"indices": {"0": 1}, "reductions": 3... | [
"def",
"training_data",
"(",
"job_id",
")",
":",
"offset",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'offset'",
",",
"0",
")",
"limit",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'limit'",
",",
"0",
")",
"cur",
".",
"execute",
"(",
"'SELEC... | Returns training_examples for a given job_id from offset to limit
If full_info parameter is greater than 0, will return extra architecture
info,
GET /jobs/139/vectors?offset=0&limit=10&full_info=1
{
"labeled_vectors": [{"vector":{"indices": {"0": 1}, "reductions": 3}, "label":0},
... | [
"Returns",
"training_examples",
"for",
"a",
"given",
"job_id",
"from",
"offset",
"to",
"limit",
"If",
"full_info",
"parameter",
"is",
"greater",
"than",
"0",
"will",
"return",
"extra",
"architecture",
"info",
"GET",
"/",
"jobs",
"/",
"139",
"/",
"vectors?offse... | python | train | 44.804878 |
erocarrera/pefile | pefile.py | https://github.com/erocarrera/pefile/blob/8a78a2e251a3f2336c232bf411133927b479edf2/pefile.py#L5341-L5461 | def relocate_image(self, new_ImageBase):
"""Apply the relocation information to the image using the provided new image base.
This method will apply the relocation information to the image. Given the new base,
all the relocations will be processed and both the raw data and the section's data
... | [
"def",
"relocate_image",
"(",
"self",
",",
"new_ImageBase",
")",
":",
"relocation_difference",
"=",
"new_ImageBase",
"-",
"self",
".",
"OPTIONAL_HEADER",
".",
"ImageBase",
"if",
"self",
".",
"OPTIONAL_HEADER",
".",
"DATA_DIRECTORY",
"[",
"5",
"]",
".",
"Size",
... | Apply the relocation information to the image using the provided new image base.
This method will apply the relocation information to the image. Given the new base,
all the relocations will be processed and both the raw data and the section's data
will be fixed accordingly.
The resultin... | [
"Apply",
"the",
"relocation",
"information",
"to",
"the",
"image",
"using",
"the",
"provided",
"new",
"image",
"base",
"."
] | python | train | 52.561983 |
angr/angr | angr/state_plugins/inspect.py | https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/state_plugins/inspect.py#L138-L184 | def check(self, state, when):
"""
Checks state `state` to see if the breakpoint should fire.
:param state: The state.
:param when: Whether the check is happening before or after the event.
:return: A boolean representing whether the checkpoint should fire.
""... | [
"def",
"check",
"(",
"self",
",",
"state",
",",
"when",
")",
":",
"ok",
"=",
"self",
".",
"enabled",
"and",
"(",
"when",
"==",
"self",
".",
"when",
"or",
"self",
".",
"when",
"==",
"BP_BOTH",
")",
"if",
"not",
"ok",
":",
"return",
"ok",
"l",
".... | Checks state `state` to see if the breakpoint should fire.
:param state: The state.
:param when: Whether the check is happening before or after the event.
:return: A boolean representing whether the checkpoint should fire. | [
"Checks",
"state",
"state",
"to",
"see",
"if",
"the",
"breakpoint",
"should",
"fire",
"."
] | python | train | 37.808511 |
wandb/client | wandb/vendor/prompt_toolkit/buffer.py | https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L1132-L1199 | def _search(self, search_state, include_current_position=False, count=1):
"""
Execute search. Return (working_index, cursor_position) tuple when this
search is applied. Returns `None` when this text cannot be found.
"""
assert isinstance(search_state, SearchState)
assert ... | [
"def",
"_search",
"(",
"self",
",",
"search_state",
",",
"include_current_position",
"=",
"False",
",",
"count",
"=",
"1",
")",
":",
"assert",
"isinstance",
"(",
"search_state",
",",
"SearchState",
")",
"assert",
"isinstance",
"(",
"count",
",",
"int",
")",
... | Execute search. Return (working_index, cursor_position) tuple when this
search is applied. Returns `None` when this text cannot be found. | [
"Execute",
"search",
".",
"Return",
"(",
"working_index",
"cursor_position",
")",
"tuple",
"when",
"this",
"search",
"is",
"applied",
".",
"Returns",
"None",
"when",
"this",
"text",
"cannot",
"be",
"found",
"."
] | python | train | 45.838235 |
vmware/pyvmomi | pyVim/task.py | https://github.com/vmware/pyvmomi/blob/3ffcb23bf77d757175c0d5216ba9a25345d824cd/pyVim/task.py#L155-L228 | def WaitForTasks(tasks,
raiseOnError=True,
si=None,
pc=None,
onProgressUpdate=None,
results=None):
"""
Wait for mulitiple tasks to complete. Much faster than calling WaitForTask
N times
"""
if not tasks:
re... | [
"def",
"WaitForTasks",
"(",
"tasks",
",",
"raiseOnError",
"=",
"True",
",",
"si",
"=",
"None",
",",
"pc",
"=",
"None",
",",
"onProgressUpdate",
"=",
"None",
",",
"results",
"=",
"None",
")",
":",
"if",
"not",
"tasks",
":",
"return",
"if",
"si",
"is",... | Wait for mulitiple tasks to complete. Much faster than calling WaitForTask
N times | [
"Wait",
"for",
"mulitiple",
"tasks",
"to",
"complete",
".",
"Much",
"faster",
"than",
"calling",
"WaitForTask",
"N",
"times"
] | python | train | 36.797297 |
openstack/horizon | horizon/exceptions.py | https://github.com/openstack/horizon/blob/5601ea9477323e599d9b766fcac1f8be742935b2/horizon/exceptions.py#L265-L348 | def handle(request, message=None, redirect=None, ignore=False,
escalate=False, log_level=None, force_log=None):
"""Centralized error handling for Horizon.
Because Horizon consumes so many different APIs with completely
different ``Exception`` types, it's necessary to have a centralized
place... | [
"def",
"handle",
"(",
"request",
",",
"message",
"=",
"None",
",",
"redirect",
"=",
"None",
",",
"ignore",
"=",
"False",
",",
"escalate",
"=",
"False",
",",
"log_level",
"=",
"None",
",",
"force_log",
"=",
"None",
")",
":",
"exc_type",
",",
"exc_value"... | Centralized error handling for Horizon.
Because Horizon consumes so many different APIs with completely
different ``Exception`` types, it's necessary to have a centralized
place for handling exceptions which may be raised.
Exceptions are roughly divided into 3 types:
#. ``UNAUTHORIZED``: Errors r... | [
"Centralized",
"error",
"handling",
"for",
"Horizon",
"."
] | python | train | 44.095238 |
sharibarboza/py_zap | py_zap/search.py | https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/search.py#L88-L94 | def _build_url(self):
"""Build url based on searching by date or by show."""
url_params = [
BASE_URL, self.category + ' ratings', self.day, self.year, self.month
]
return SEARCH_URL.format(*url_params) | [
"def",
"_build_url",
"(",
"self",
")",
":",
"url_params",
"=",
"[",
"BASE_URL",
",",
"self",
".",
"category",
"+",
"' ratings'",
",",
"self",
".",
"day",
",",
"self",
".",
"year",
",",
"self",
".",
"month",
"]",
"return",
"SEARCH_URL",
".",
"format",
... | Build url based on searching by date or by show. | [
"Build",
"url",
"based",
"on",
"searching",
"by",
"date",
"or",
"by",
"show",
"."
] | python | train | 34.285714 |
readbeyond/aeneas | aeneas/idsortingalgorithm.py | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/idsortingalgorithm.py#L79-L109 | def sort(self, ids):
"""
Sort the given list of identifiers,
returning a new (sorted) list.
:param list ids: the list of identifiers to be sorted
:rtype: list
"""
def extract_int(string):
"""
Extract an integer from the given string.
... | [
"def",
"sort",
"(",
"self",
",",
"ids",
")",
":",
"def",
"extract_int",
"(",
"string",
")",
":",
"\"\"\"\n Extract an integer from the given string.\n\n :param string string: the identifier string\n :rtype: int\n \"\"\"",
"return",
"int",
... | Sort the given list of identifiers,
returning a new (sorted) list.
:param list ids: the list of identifiers to be sorted
:rtype: list | [
"Sort",
"the",
"given",
"list",
"of",
"identifiers",
"returning",
"a",
"new",
"(",
"sorted",
")",
"list",
"."
] | python | train | 35.677419 |
materialsproject/pymatgen | pymatgen/util/coord.py | https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/util/coord.py#L214-L233 | def find_in_coord_list_pbc(fcoord_list, fcoord, atol=1e-8):
"""
Get the indices of all points in a fractional coord list that are
equal to a fractional coord (with a tolerance), taking into account
periodic boundary conditions.
Args:
fcoord_list: List of fractional coords
fcoord: A ... | [
"def",
"find_in_coord_list_pbc",
"(",
"fcoord_list",
",",
"fcoord",
",",
"atol",
"=",
"1e-8",
")",
":",
"if",
"len",
"(",
"fcoord_list",
")",
"==",
"0",
":",
"return",
"[",
"]",
"fcoords",
"=",
"np",
".",
"tile",
"(",
"fcoord",
",",
"(",
"len",
"(",
... | Get the indices of all points in a fractional coord list that are
equal to a fractional coord (with a tolerance), taking into account
periodic boundary conditions.
Args:
fcoord_list: List of fractional coords
fcoord: A specific fractional coord to test.
atol: Absolute tolerance. Def... | [
"Get",
"the",
"indices",
"of",
"all",
"points",
"in",
"a",
"fractional",
"coord",
"list",
"that",
"are",
"equal",
"to",
"a",
"fractional",
"coord",
"(",
"with",
"a",
"tolerance",
")",
"taking",
"into",
"account",
"periodic",
"boundary",
"conditions",
"."
] | python | train | 35.35 |
mcs07/ChemDataExtractor | chemdataextractor/nlp/tokenize.py | https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tokenize.py#L247-L251 | def _split_span(self, span, index, length=0):
"""Split a span into two or three separate spans at certain indices."""
offset = span[1] + index if index < 0 else span[0] + index
# log.debug([(span[0], offset), (offset, offset + length), (offset + length, span[1])])
return [(span[0], offse... | [
"def",
"_split_span",
"(",
"self",
",",
"span",
",",
"index",
",",
"length",
"=",
"0",
")",
":",
"offset",
"=",
"span",
"[",
"1",
"]",
"+",
"index",
"if",
"index",
"<",
"0",
"else",
"span",
"[",
"0",
"]",
"+",
"index",
"# log.debug([(span[0], offset)... | Split a span into two or three separate spans at certain indices. | [
"Split",
"a",
"span",
"into",
"two",
"or",
"three",
"separate",
"spans",
"at",
"certain",
"indices",
"."
] | python | train | 74.8 |
rshk/python-libxdo | xdo/__init__.py | https://github.com/rshk/python-libxdo/blob/84cafa5943b005bc423edd28203a5266b3579ac3/xdo/__init__.py#L564-L574 | def get_window_location(self, window):
"""
Get a window's location.
"""
screen_ret = Screen()
x_ret = ctypes.c_int(0)
y_ret = ctypes.c_int(0)
_libxdo.xdo_get_window_location(
self._xdo, window, ctypes.byref(x_ret), ctypes.byref(y_ret),
ctyp... | [
"def",
"get_window_location",
"(",
"self",
",",
"window",
")",
":",
"screen_ret",
"=",
"Screen",
"(",
")",
"x_ret",
"=",
"ctypes",
".",
"c_int",
"(",
"0",
")",
"y_ret",
"=",
"ctypes",
".",
"c_int",
"(",
"0",
")",
"_libxdo",
".",
"xdo_get_window_location"... | Get a window's location. | [
"Get",
"a",
"window",
"s",
"location",
"."
] | python | train | 36.363636 |
MIT-LCP/wfdb-python | wfdb/io/_header.py | https://github.com/MIT-LCP/wfdb-python/blob/cc8c9e9e44f10af961b7a9d8ae03708b31ac8a8c/wfdb/io/_header.py#L306-L342 | def get_write_fields(self):
"""
Get the list of fields used to write the header, separating
record and signal specification fields. Returns the default
required fields, the user defined fields,
and their dependencies.
Does NOT include `d_signal` or `e_d_signal`.
... | [
"def",
"get_write_fields",
"(",
"self",
")",
":",
"# Record specification fields",
"rec_write_fields",
"=",
"self",
".",
"get_write_subset",
"(",
"'record'",
")",
"# Add comments if any",
"if",
"self",
".",
"comments",
"!=",
"None",
":",
"rec_write_fields",
".",
"ap... | Get the list of fields used to write the header, separating
record and signal specification fields. Returns the default
required fields, the user defined fields,
and their dependencies.
Does NOT include `d_signal` or `e_d_signal`.
Returns
-------
rec_write_field... | [
"Get",
"the",
"list",
"of",
"fields",
"used",
"to",
"write",
"the",
"header",
"separating",
"record",
"and",
"signal",
"specification",
"fields",
".",
"Returns",
"the",
"default",
"required",
"fields",
"the",
"user",
"defined",
"fields",
"and",
"their",
"depen... | python | train | 31.081081 |
mitsei/dlkit | dlkit/json_/repository/searches.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/repository/searches.py#L218-L229 | def get_compositions(self):
"""Gets the composition list resulting from a search.
return: (osid.repository.CompositionList) - the composition list
raise: IllegalState - the list has already been retrieved
*compliance: mandatory -- This method must be implemented.*
"""
... | [
"def",
"get_compositions",
"(",
"self",
")",
":",
"if",
"self",
".",
"retrieved",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'List has already been retrieved.'",
")",
"self",
".",
"retrieved",
"=",
"True",
"return",
"objects",
".",
"CompositionList",
"("... | Gets the composition list resulting from a search.
return: (osid.repository.CompositionList) - the composition list
raise: IllegalState - the list has already been retrieved
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"composition",
"list",
"resulting",
"from",
"a",
"search",
"."
] | python | train | 42.333333 |
ui/django-post_office | post_office/lockfile.py | https://github.com/ui/django-post_office/blob/03e1ffb69829b475402f0f3ecd9f8a90af7da4bd/post_office/lockfile.py#L133-L144 | def release(self):
"""Try to delete the lock files. Doesn't matter if we fail"""
if self.lock_filename != self.pid_filename:
try:
os.unlink(self.lock_filename)
except OSError:
pass
try:
os.remove(self.pid_filename)
exce... | [
"def",
"release",
"(",
"self",
")",
":",
"if",
"self",
".",
"lock_filename",
"!=",
"self",
".",
"pid_filename",
":",
"try",
":",
"os",
".",
"unlink",
"(",
"self",
".",
"lock_filename",
")",
"except",
"OSError",
":",
"pass",
"try",
":",
"os",
".",
"re... | Try to delete the lock files. Doesn't matter if we fail | [
"Try",
"to",
"delete",
"the",
"lock",
"files",
".",
"Doesn",
"t",
"matter",
"if",
"we",
"fail"
] | python | train | 28.083333 |
adafruit/Adafruit_Python_GPIO | Adafruit_GPIO/SPI.py | https://github.com/adafruit/Adafruit_Python_GPIO/blob/a92a23d6b5869663b2bc1ccf78bb11585076a9c4/Adafruit_GPIO/SPI.py#L224-L246 | def write(self, data, assert_ss=True, deassert_ss=True):
"""Half-duplex SPI write. If assert_ss is True, the SS line will be
asserted low, the specified bytes will be clocked out the MOSI line, and
if deassert_ss is True the SS line be put back high.
"""
# Fail MOSI is not speci... | [
"def",
"write",
"(",
"self",
",",
"data",
",",
"assert_ss",
"=",
"True",
",",
"deassert_ss",
"=",
"True",
")",
":",
"# Fail MOSI is not specified.",
"if",
"self",
".",
"_mosi",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Write attempted with no MOSI pin s... | Half-duplex SPI write. If assert_ss is True, the SS line will be
asserted low, the specified bytes will be clocked out the MOSI line, and
if deassert_ss is True the SS line be put back high. | [
"Half",
"-",
"duplex",
"SPI",
"write",
".",
"If",
"assert_ss",
"is",
"True",
"the",
"SS",
"line",
"will",
"be",
"asserted",
"low",
"the",
"specified",
"bytes",
"will",
"be",
"clocked",
"out",
"the",
"MOSI",
"line",
"and",
"if",
"deassert_ss",
"is",
"True... | python | valid | 47 |
huggingface/pytorch-pretrained-BERT | pytorch_pretrained_bert/modeling.py | https://github.com/huggingface/pytorch-pretrained-BERT/blob/b832d5bb8a6dfc5965015b828e577677eace601e/pytorch_pretrained_bert/modeling.py#L51-L115 | def load_tf_weights_in_bert(model, tf_checkpoint_path):
""" Load tf checkpoints in a pytorch model
"""
try:
import re
import numpy as np
import tensorflow as tf
except ImportError:
print("Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please ... | [
"def",
"load_tf_weights_in_bert",
"(",
"model",
",",
"tf_checkpoint_path",
")",
":",
"try",
":",
"import",
"re",
"import",
"numpy",
"as",
"np",
"import",
"tensorflow",
"as",
"tf",
"except",
"ImportError",
":",
"print",
"(",
"\"Loading a TensorFlow models in PyTorch,... | Load tf checkpoints in a pytorch model | [
"Load",
"tf",
"checkpoints",
"in",
"a",
"pytorch",
"model"
] | python | train | 39.476923 |
6809/MC6809 | MC6809/components/mc6809_speedlimited.py | https://github.com/6809/MC6809/blob/6ba2f5106df46689017b5d0b6d84d43b7ee6a240/MC6809/components/mc6809_speedlimited.py#L34-L58 | def delayed_burst_run(self, target_cycles_per_sec):
""" Run CPU not faster than given speedlimit """
old_cycles = self.cycles
start_time = time.time()
self.burst_run()
is_duration = time.time() - start_time
new_cycles = self.cycles - old_cycles
try:
... | [
"def",
"delayed_burst_run",
"(",
"self",
",",
"target_cycles_per_sec",
")",
":",
"old_cycles",
"=",
"self",
".",
"cycles",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"burst_run",
"(",
")",
"is_duration",
"=",
"time",
".",
"time",
"(",
... | Run CPU not faster than given speedlimit | [
"Run",
"CPU",
"not",
"faster",
"than",
"given",
"speedlimit"
] | python | train | 34.08 |
totalgood/nlpia | src/nlpia/regexes.py | https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/regexes.py#L127-L135 | def to_tsv():
""" Save all regular expressions to a tsv file so they can be more easily copy/pasted in Sublime """
with open(os.path.join(DATA_PATH, 'regexes.tsv'), mode='wt') as fout:
vars = copy.copy(tuple(globals().items()))
for k, v in vars:
if k.lower().startswith('cre_'):
... | [
"def",
"to_tsv",
"(",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"DATA_PATH",
",",
"'regexes.tsv'",
")",
",",
"mode",
"=",
"'wt'",
")",
"as",
"fout",
":",
"vars",
"=",
"copy",
".",
"copy",
"(",
"tuple",
"(",
"globals",
"(... | Save all regular expressions to a tsv file so they can be more easily copy/pasted in Sublime | [
"Save",
"all",
"regular",
"expressions",
"to",
"a",
"tsv",
"file",
"so",
"they",
"can",
"be",
"more",
"easily",
"copy",
"/",
"pasted",
"in",
"Sublime"
] | python | train | 52.444444 |
klichukb/django-migrate-sql | migrate_sql/graph.py | https://github.com/klichukb/django-migrate-sql/blob/be48ff2c9283404e3d951128c459c3496d1ba25d/migrate_sql/graph.py#L54-L77 | def build_graph(self):
"""
Read lazy dependency list and build graph.
"""
for child, parents in self.dependencies.items():
if child not in self.nodes:
raise NodeNotFoundError(
"App %s SQL item dependencies reference nonexistent child node %... | [
"def",
"build_graph",
"(",
"self",
")",
":",
"for",
"child",
",",
"parents",
"in",
"self",
".",
"dependencies",
".",
"items",
"(",
")",
":",
"if",
"child",
"not",
"in",
"self",
".",
"nodes",
":",
"raise",
"NodeNotFoundError",
"(",
"\"App %s SQL item depend... | Read lazy dependency list and build graph. | [
"Read",
"lazy",
"dependency",
"list",
"and",
"build",
"graph",
"."
] | python | train | 42.625 |
Terrance/SkPy | skpy/conn.py | https://github.com/Terrance/SkPy/blob/0f9489c94e8ec4d3effab4314497428872a80ad1/skpy/conn.py#L749-L830 | def getMac256Hash(challenge, appId="msmsgs@msnmsgr.com", key="Q1P7W2E4J9R8U3S5"):
"""
Generate the lock-and-key response, needed to acquire registration tokens.
"""
clearText = challenge + appId
clearText += "0" * (8 - len(clearText) % 8)
def int32ToHexString(n):
... | [
"def",
"getMac256Hash",
"(",
"challenge",
",",
"appId",
"=",
"\"msmsgs@msnmsgr.com\"",
",",
"key",
"=",
"\"Q1P7W2E4J9R8U3S5\"",
")",
":",
"clearText",
"=",
"challenge",
"+",
"appId",
"clearText",
"+=",
"\"0\"",
"*",
"(",
"8",
"-",
"len",
"(",
"clearText",
")... | Generate the lock-and-key response, needed to acquire registration tokens. | [
"Generate",
"the",
"lock",
"-",
"and",
"-",
"key",
"response",
"needed",
"to",
"acquire",
"registration",
"tokens",
"."
] | python | test | 35.487805 |
aws/sagemaker-containers | src/sagemaker_containers/_mpi.py | https://github.com/aws/sagemaker-containers/blob/0030f07abbaf22a55d986d97274d7a8d1aa1f10c/src/sagemaker_containers/_mpi.py#L230-L238 | def _parse_custom_mpi_options(custom_mpi_options):
# type: (str) -> Tuple[argparse.Namespace, List[str]]
"""Parse custom MPI options provided by user. Known options default value will be overridden
and unknown options would be identified separately."""
parser = argparse.ArgumentParser()
parser.add_... | [
"def",
"_parse_custom_mpi_options",
"(",
"custom_mpi_options",
")",
":",
"# type: (str) -> Tuple[argparse.Namespace, List[str]]",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--NCCL_DEBUG'",
",",
"default",
"=",
"\"INFO... | Parse custom MPI options provided by user. Known options default value will be overridden
and unknown options would be identified separately. | [
"Parse",
"custom",
"MPI",
"options",
"provided",
"by",
"user",
".",
"Known",
"options",
"default",
"value",
"will",
"be",
"overridden",
"and",
"unknown",
"options",
"would",
"be",
"identified",
"separately",
"."
] | python | train | 47.333333 |
saltstack/salt | salt/modules/win_psget.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_psget.py#L157-L199 | def install(name, minimum_version=None, required_version=None, scope=None,
repository=None):
'''
Install a Powershell module from powershell gallery on the system.
:param name: Name of a Powershell module
:type name: ``str``
:param minimum_version: The maximum version to install, e.g.... | [
"def",
"install",
"(",
"name",
",",
"minimum_version",
"=",
"None",
",",
"required_version",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"repository",
"=",
"None",
")",
":",
"# Putting quotes around the parameter protects against command injection",
"flags",
"=",
"... | Install a Powershell module from powershell gallery on the system.
:param name: Name of a Powershell module
:type name: ``str``
:param minimum_version: The maximum version to install, e.g. 1.23.2
:type minimum_version: ``str``
:param required_version: Install a specific version
:type requi... | [
"Install",
"a",
"Powershell",
"module",
"from",
"powershell",
"gallery",
"on",
"the",
"system",
"."
] | python | train | 31.953488 |
gofed/gofedlib | gofedlib/repository/gitlocalclient.py | https://github.com/gofed/gofedlib/blob/0674c248fe3d8706f98f912996b65af469f96b10/gofedlib/repository/gitlocalclient.py#L48-L71 | def commits(self, branch, since = 0, to = int(time.time()) + 86400):
"""For given branch return a list of commits.
Each commit contains basic information about itself.
:param branch: git branch
:type branch: [str]{}
:param since: minimal timestamp for commit's commit date
:type since: int
:param to: ma... | [
"def",
"commits",
"(",
"self",
",",
"branch",
",",
"since",
"=",
"0",
",",
"to",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"+",
"86400",
")",
":",
"# checkout the branch",
"self",
".",
"repo",
".",
"create_head",
"(",
"branch",
",",
"\"r... | For given branch return a list of commits.
Each commit contains basic information about itself.
:param branch: git branch
:type branch: [str]{}
:param since: minimal timestamp for commit's commit date
:type since: int
:param to: maximal timestamp for commit's commit date
:type to: int | [
"For",
"given",
"branch",
"return",
"a",
"list",
"of",
"commits",
".",
"Each",
"commit",
"contains",
"basic",
"information",
"about",
"itself",
"."
] | python | train | 32.416667 |
gwpy/gwpy | gwpy/detector/channel.py | https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/detector/channel.py#L675-L699 | def _split_names(namestr):
"""Split a comma-separated list of channel names.
"""
out = []
namestr = QUOTE_REGEX.sub('', namestr)
while True:
namestr = namestr.strip('\' \n')
if ',' not in namestr:
break
for nds2type in io_nds2.N... | [
"def",
"_split_names",
"(",
"namestr",
")",
":",
"out",
"=",
"[",
"]",
"namestr",
"=",
"QUOTE_REGEX",
".",
"sub",
"(",
"''",
",",
"namestr",
")",
"while",
"True",
":",
"namestr",
"=",
"namestr",
".",
"strip",
"(",
"'\\' \\n'",
")",
"if",
"','",
"not"... | Split a comma-separated list of channel names. | [
"Split",
"a",
"comma",
"-",
"separated",
"list",
"of",
"channel",
"names",
"."
] | python | train | 38.36 |
VIVelev/PyDojoML | dojo/svm/libsvm/svmutil.py | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/svm/libsvm/svmutil.py#L18-L29 | def svm_load_model(model_file_name):
"""
svm_load_model(model_file_name) -> model
Load a LIBSVM model from model_file_name and return.
"""
model = libsvm.svm_load_model(model_file_name.encode())
if not model:
print("can't open model file %s" % model_file_name)
return None
model = toPyModel(model)
return mo... | [
"def",
"svm_load_model",
"(",
"model_file_name",
")",
":",
"model",
"=",
"libsvm",
".",
"svm_load_model",
"(",
"model_file_name",
".",
"encode",
"(",
")",
")",
"if",
"not",
"model",
":",
"print",
"(",
"\"can't open model file %s\"",
"%",
"model_file_name",
")",
... | svm_load_model(model_file_name) -> model
Load a LIBSVM model from model_file_name and return. | [
"svm_load_model",
"(",
"model_file_name",
")",
"-",
">",
"model"
] | python | train | 26 |
dipcode-software/django-ajax-cbv | ajax_cbv/mixins.py | https://github.com/dipcode-software/django-ajax-cbv/blob/a723eaa90490e57f1b2dfbd8d10905b9e2541f88/ajax_cbv/mixins.py#L82-L91 | def form_invalid(self, form, prefix=None):
""" If form invalid return error list in JSON response """
response = super(FormAjaxMixin, self).form_invalid(form)
if self.request.is_ajax():
data = {
"errors_list": self.add_prefix(form.errors, prefix),
}
... | [
"def",
"form_invalid",
"(",
"self",
",",
"form",
",",
"prefix",
"=",
"None",
")",
":",
"response",
"=",
"super",
"(",
"FormAjaxMixin",
",",
"self",
")",
".",
"form_invalid",
"(",
"form",
")",
"if",
"self",
".",
"request",
".",
"is_ajax",
"(",
")",
":... | If form invalid return error list in JSON response | [
"If",
"form",
"invalid",
"return",
"error",
"list",
"in",
"JSON",
"response"
] | python | train | 47.6 |
apache/incubator-mxnet | python/mxnet/contrib/onnx/mx2onnx/_op_translations.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/contrib/onnx/mx2onnx/_op_translations.py#L753-L779 | def convert_leakyrelu(node, **kwargs):
"""Map MXNet's LeakyReLU operator attributes to onnx's Elu/LeakyRelu/PRelu operators
based on the input node's attributes and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
act_type = attrs.get("act_type", "leaky")
alpha =... | [
"def",
"convert_leakyrelu",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"act_type",
"=",
"attrs",
".",
"get",
"(",
"\"act_type\"",
",",
"\"leaky\"",
")",
... | Map MXNet's LeakyReLU operator attributes to onnx's Elu/LeakyRelu/PRelu operators
based on the input node's attributes and return the created node. | [
"Map",
"MXNet",
"s",
"LeakyReLU",
"operator",
"attributes",
"to",
"onnx",
"s",
"Elu",
"/",
"LeakyRelu",
"/",
"PRelu",
"operators",
"based",
"on",
"the",
"input",
"node",
"s",
"attributes",
"and",
"return",
"the",
"created",
"node",
"."
] | python | train | 31.111111 |
Microsoft/azure-devops-python-api | azure-devops/azure/devops/v5_0/accounts/accounts_client.py | https://github.com/Microsoft/azure-devops-python-api/blob/4777ffda2f5052fabbaddb2abe9cb434e0cf1aa8/azure-devops/azure/devops/v5_0/accounts/accounts_client.py#L28-L47 | def get_accounts(self, owner_id=None, member_id=None, properties=None):
"""GetAccounts.
Get a list of accounts for a specific owner or a specific member.
:param str owner_id: ID for the owner of the accounts.
:param str member_id: ID for a member of the accounts.
:param str prope... | [
"def",
"get_accounts",
"(",
"self",
",",
"owner_id",
"=",
"None",
",",
"member_id",
"=",
"None",
",",
"properties",
"=",
"None",
")",
":",
"query_parameters",
"=",
"{",
"}",
"if",
"owner_id",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"'ownerId'",
... | GetAccounts.
Get a list of accounts for a specific owner or a specific member.
:param str owner_id: ID for the owner of the accounts.
:param str member_id: ID for a member of the accounts.
:param str properties:
:rtype: [Account] | [
"GetAccounts",
".",
"Get",
"a",
"list",
"of",
"accounts",
"for",
"a",
"specific",
"owner",
"or",
"a",
"specific",
"member",
".",
":",
"param",
"str",
"owner_id",
":",
"ID",
"for",
"the",
"owner",
"of",
"the",
"accounts",
".",
":",
"param",
"str",
"memb... | python | train | 54.4 |
klen/pylama | pylama/lint/pylama_pycodestyle.py | https://github.com/klen/pylama/blob/f436ccc6b55b33381a295ded753e467953cf4379/pylama/lint/pylama_pycodestyle.py#L18-L36 | def run(path, code=None, params=None, **meta):
"""Check code with pycodestyle.
:return list: List of errors.
"""
parser = get_parser()
for option in parser.option_list:
if option.dest and option.dest in params:
value = params[option.dest]
... | [
"def",
"run",
"(",
"path",
",",
"code",
"=",
"None",
",",
"params",
"=",
"None",
",",
"*",
"*",
"meta",
")",
":",
"parser",
"=",
"get_parser",
"(",
")",
"for",
"option",
"in",
"parser",
".",
"option_list",
":",
"if",
"option",
".",
"dest",
"and",
... | Check code with pycodestyle.
:return list: List of errors. | [
"Check",
"code",
"with",
"pycodestyle",
"."
] | python | train | 40.157895 |
aquatix/ns-api | ns_api.py | https://github.com/aquatix/ns-api/blob/9b3379f8df6217132f457c4363457c16321c2448/ns_api.py#L795-L804 | def get_departures(self, station):
"""
Fetch the current departure times from this station
http://webservices.ns.nl/ns-api-avt?station=${Naam of afkorting Station}
@param station: station to lookup
"""
url = 'http://webservices.ns.nl/ns-api-avt?station=' + station
... | [
"def",
"get_departures",
"(",
"self",
",",
"station",
")",
":",
"url",
"=",
"'http://webservices.ns.nl/ns-api-avt?station='",
"+",
"station",
"raw_departures",
"=",
"self",
".",
"_request",
"(",
"'GET'",
",",
"url",
")",
"return",
"self",
".",
"parse_departures",
... | Fetch the current departure times from this station
http://webservices.ns.nl/ns-api-avt?station=${Naam of afkorting Station}
@param station: station to lookup | [
"Fetch",
"the",
"current",
"departure",
"times",
"from",
"this",
"station",
"http",
":",
"//",
"webservices",
".",
"ns",
".",
"nl",
"/",
"ns",
"-",
"api",
"-",
"avt?station",
"=",
"$",
"{",
"Naam",
"of",
"afkorting",
"Station",
"}"
] | python | train | 40.8 |
baguette-io/baguette-utils | sel/request.py | https://github.com/baguette-io/baguette-utils/blob/bf6b82811167f9268b5a1bbbdece411158f96d1e/sel/request.py#L74-L99 | def all(self, endpoint, *args, **kwargs):
"""Retrieve all the data of a paginated endpoint, using GET.
:returns: The endpoint unpaginated data
:rtype: dict
"""
# 1. Initialize the pagination parameters.
kwargs.setdefault('params', {})['offset'] = 0
kwargs.setdefau... | [
"def",
"all",
"(",
"self",
",",
"endpoint",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# 1. Initialize the pagination parameters.",
"kwargs",
".",
"setdefault",
"(",
"'params'",
",",
"{",
"}",
")",
"[",
"'offset'",
"]",
"=",
"0",
"kwargs",
"."... | Retrieve all the data of a paginated endpoint, using GET.
:returns: The endpoint unpaginated data
:rtype: dict | [
"Retrieve",
"all",
"the",
"data",
"of",
"a",
"paginated",
"endpoint",
"using",
"GET",
".",
":",
"returns",
":",
"The",
"endpoint",
"unpaginated",
"data",
":",
"rtype",
":",
"dict"
] | python | train | 42.730769 |
openpaperwork/paperwork-backend | paperwork_backend/img/page.py | https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/img/page.py#L95-L120 | def __get_boxes(self):
"""
Get all the word boxes of this page.
"""
boxfile = self.__box_path
try:
box_builder = pyocr.builders.LineBoxBuilder()
with self.fs.open(boxfile, 'r') as file_desc:
boxes = box_builder.read_file(file_desc)
... | [
"def",
"__get_boxes",
"(",
"self",
")",
":",
"boxfile",
"=",
"self",
".",
"__box_path",
"try",
":",
"box_builder",
"=",
"pyocr",
".",
"builders",
".",
"LineBoxBuilder",
"(",
")",
"with",
"self",
".",
"fs",
".",
"open",
"(",
"boxfile",
",",
"'r'",
")",
... | Get all the word boxes of this page. | [
"Get",
"all",
"the",
"word",
"boxes",
"of",
"this",
"page",
"."
] | python | train | 38.846154 |
edwards-lab/MVtest | scripts/mvmany.py | https://github.com/edwards-lab/MVtest/blob/fe8cf627464ef59d68b7eda628a19840d033882f/scripts/mvmany.py#L45-L73 | def generate_jobs(args, job_list, argument_string):
"""Generate actual scripts to be submitted to the cluster
:param args: argparse argument collection
:param job_list: dictionary containing each each job to be submitted
:param argument_string: string containing general arguments to be used by mvtest.p... | [
"def",
"generate_jobs",
"(",
"args",
",",
"job_list",
",",
"argument_string",
")",
":",
"mvtest_path",
"=",
"args",
".",
"mvpath",
"template",
"=",
"\"\"",
".",
"join",
"(",
"args",
".",
"template",
".",
"readlines",
"(",
")",
")",
"logpath",
"=",
"os",
... | Generate actual scripts to be submitted to the cluster
:param args: argparse argument collection
:param job_list: dictionary containing each each job to be submitted
:param argument_string: string containing general arguments to be used by mvtest.py during execution
:return: None | [
"Generate",
"actual",
"scripts",
"to",
"be",
"submitted",
"to",
"the",
"cluster"
] | python | train | 39.482759 |
soimort/you-get | src/you_get/__main__.py | https://github.com/soimort/you-get/blob/b746ac01c9f39de94cac2d56f665285b0523b974/src/you_get/__main__.py#L24-L85 | def main_dev(**kwargs):
"""Main entry point.
you-get-dev
"""
# Get (branch, commit) if running from a git repo.
head = git.get_head(kwargs['repo_path'])
# Get options and arguments.
try:
opts, args = getopt.getopt(sys.argv[1:], _short_options, _options)
except getopt.GetoptErro... | [
"def",
"main_dev",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Get (branch, commit) if running from a git repo.",
"head",
"=",
"git",
".",
"get_head",
"(",
"kwargs",
"[",
"'repo_path'",
"]",
")",
"# Get options and arguments.",
"try",
":",
"opts",
",",
"args",
"=",
"g... | Main entry point.
you-get-dev | [
"Main",
"entry",
"point",
".",
"you",
"-",
"get",
"-",
"dev"
] | python | test | 32.564516 |
Anaconda-Platform/anaconda-client | binstar_client/utils/conda.py | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/utils/conda.py#L43-L64 | def get_conda_root():
"""Get the PREFIX of the conda installation.
Returns:
str: the ROOT_PREFIX of the conda installation
"""
try:
# Fast-path
# We're in the root environment
conda_root = _import_conda_root()
except ImportError:
# We're not in the root envir... | [
"def",
"get_conda_root",
"(",
")",
":",
"try",
":",
"# Fast-path",
"# We're in the root environment",
"conda_root",
"=",
"_import_conda_root",
"(",
")",
"except",
"ImportError",
":",
"# We're not in the root environment.",
"envs_dir",
"=",
"dirname",
"(",
"CONDA_PREFIX",
... | Get the PREFIX of the conda installation.
Returns:
str: the ROOT_PREFIX of the conda installation | [
"Get",
"the",
"PREFIX",
"of",
"the",
"conda",
"installation",
"."
] | python | train | 33.136364 |
noirbizarre/flask-fs | flask_fs/backends/local.py | https://github.com/noirbizarre/flask-fs/blob/092e9327384b8411c9bb38ca257ecb558584d201/flask_fs/backends/local.py#L132-L142 | def get_metadata(self, filename):
'''Fetch all available metadata'''
dest = self.path(filename)
with open(dest, 'rb', buffering=0) as f:
checksum = 'sha1:{0}'.format(sha1(f))
return {
'checksum': checksum,
'size': os.path.getsize(dest),
'mi... | [
"def",
"get_metadata",
"(",
"self",
",",
"filename",
")",
":",
"dest",
"=",
"self",
".",
"path",
"(",
"filename",
")",
"with",
"open",
"(",
"dest",
",",
"'rb'",
",",
"buffering",
"=",
"0",
")",
"as",
"f",
":",
"checksum",
"=",
"'sha1:{0}'",
".",
"f... | Fetch all available metadata | [
"Fetch",
"all",
"available",
"metadata"
] | python | train | 38 |
frascoweb/frasco | frasco/views.py | https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/views.py#L89-L93 | def register(self, target):
"""Registers url_rules on the blueprint
"""
for rule, options in self.url_rules:
target.add_url_rule(rule, self.name, self.dispatch_request, **options) | [
"def",
"register",
"(",
"self",
",",
"target",
")",
":",
"for",
"rule",
",",
"options",
"in",
"self",
".",
"url_rules",
":",
"target",
".",
"add_url_rule",
"(",
"rule",
",",
"self",
".",
"name",
",",
"self",
".",
"dispatch_request",
",",
"*",
"*",
"o... | Registers url_rules on the blueprint | [
"Registers",
"url_rules",
"on",
"the",
"blueprint"
] | python | train | 42.2 |
markovmodel/PyEMMA | pyemma/_base/estimator.py | https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/estimator.py#L127-L191 | def _estimate_param_scan_worker(estimator, params, X, evaluate, evaluate_args,
failfast, return_exceptions):
""" Method that runs estimation for several parameter settings.
Defined as a worker for parallelization
"""
# run estimation
model = None
try: # catch a... | [
"def",
"_estimate_param_scan_worker",
"(",
"estimator",
",",
"params",
",",
"X",
",",
"evaluate",
",",
"evaluate_args",
",",
"failfast",
",",
"return_exceptions",
")",
":",
"# run estimation",
"model",
"=",
"None",
"try",
":",
"# catch any exception",
"estimator",
... | Method that runs estimation for several parameter settings.
Defined as a worker for parallelization | [
"Method",
"that",
"runs",
"estimation",
"for",
"several",
"parameter",
"settings",
"."
] | python | train | 34.738462 |
adafruit/Adafruit_Python_BluefruitLE | Adafruit_BluefruitLE/corebluetooth/provider.py | https://github.com/adafruit/Adafruit_Python_BluefruitLE/blob/34fc6f596371b961628369d78ce836950514062f/Adafruit_BluefruitLE/corebluetooth/provider.py#L272-L284 | def _user_thread_main(self, target):
"""Main entry point for the thread that will run user's code."""
try:
# Run user's code.
return_code = target()
# Assume good result (0 return code) if none is returned.
if return_code is None:
return_co... | [
"def",
"_user_thread_main",
"(",
"self",
",",
"target",
")",
":",
"try",
":",
"# Run user's code.",
"return_code",
"=",
"target",
"(",
")",
"# Assume good result (0 return code) if none is returned.",
"if",
"return_code",
"is",
"None",
":",
"return_code",
"=",
"0",
... | Main entry point for the thread that will run user's code. | [
"Main",
"entry",
"point",
"for",
"the",
"thread",
"that",
"will",
"run",
"user",
"s",
"code",
"."
] | python | valid | 48.692308 |
nderkach/airbnb-python | airbnb/api.py | https://github.com/nderkach/airbnb-python/blob/0b3ed69518e41383eca93ae11b24247f3cc69a27/airbnb/api.py#L332-L367 | def get_homes(self, query=None, gps_lat=None, gps_lng=None, offset=0, items_per_grid=8):
"""
Search listings with
* Query (e.g. query="Lisbon, Portugal") or
* Location (e.g. gps_lat=55.6123352&gps_lng=37.7117917)
"""
params = {
'is_guided_search': 'tru... | [
"def",
"get_homes",
"(",
"self",
",",
"query",
"=",
"None",
",",
"gps_lat",
"=",
"None",
",",
"gps_lng",
"=",
"None",
",",
"offset",
"=",
"0",
",",
"items_per_grid",
"=",
"8",
")",
":",
"params",
"=",
"{",
"'is_guided_search'",
":",
"'true'",
",",
"'... | Search listings with
* Query (e.g. query="Lisbon, Portugal") or
* Location (e.g. gps_lat=55.6123352&gps_lng=37.7117917) | [
"Search",
"listings",
"with",
"*",
"Query",
"(",
"e",
".",
"g",
".",
"query",
"=",
"Lisbon",
"Portugal",
")",
"or",
"*",
"Location",
"(",
"e",
".",
"g",
".",
"gps_lat",
"=",
"55",
".",
"6123352&gps_lng",
"=",
"37",
".",
"7117917",
")"
] | python | train | 33.194444 |
ibis-project/ibis | ibis/bigquery/api.py | https://github.com/ibis-project/ibis/blob/1e39a5fd9ef088b45c155e8a5f541767ee8ef2e7/ibis/bigquery/api.py#L56-L90 | def connect(
project_id: Optional[str] = None,
dataset_id: Optional[str] = None,
credentials: Optional[google.auth.credentials.Credentials] = None,
) -> BigQueryClient:
"""Create a BigQueryClient for use with Ibis.
Parameters
----------
project_id : str
A BigQuery project id.
da... | [
"def",
"connect",
"(",
"project_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"dataset_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"credentials",
":",
"Optional",
"[",
"google",
".",
"auth",
".",
"credentials",
".",
"Credentials",... | Create a BigQueryClient for use with Ibis.
Parameters
----------
project_id : str
A BigQuery project id.
dataset_id : str
A dataset id that lives inside of the project indicated by
`project_id`.
credentials : google.auth.credentials.Credentials
Returns
-------
B... | [
"Create",
"a",
"BigQueryClient",
"for",
"use",
"with",
"Ibis",
"."
] | python | train | 27.514286 |
spyder-ide/spyder | spyder/plugins/ipythonconsole/plugin.py | https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/ipythonconsole/plugin.py#L1298-L1319 | def rename_tabs_after_change(self, given_name):
"""Rename tabs after a change in name."""
client = self.get_current_client()
# Prevent renames that want to assign the same name of
# a previous tab
repeated = False
for cl in self.get_clients():
if id(c... | [
"def",
"rename_tabs_after_change",
"(",
"self",
",",
"given_name",
")",
":",
"client",
"=",
"self",
".",
"get_current_client",
"(",
")",
"# Prevent renames that want to assign the same name of\r",
"# a previous tab\r",
"repeated",
"=",
"False",
"for",
"cl",
"in",
"self"... | Rename tabs after a change in name. | [
"Rename",
"tabs",
"after",
"a",
"change",
"in",
"name",
"."
] | python | train | 40.045455 |
jaywink/federation | federation/protocols/activitypub/protocol.py | https://github.com/jaywink/federation/blob/59d31bb37e662891dbea72c1dee05dc53146c78b/federation/protocols/activitypub/protocol.py#L47-L61 | def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]:
"""
Build POST data for sending out to remotes.
:param entity: The outbound ready entity for this protocol.
:param from_user: The user sending this payload. Must have ``private... | [
"def",
"build_send",
"(",
"self",
",",
"entity",
":",
"BaseEntity",
",",
"from_user",
":",
"UserType",
",",
"to_user_key",
":",
"RsaKey",
"=",
"None",
")",
"->",
"Union",
"[",
"str",
",",
"Dict",
"]",
":",
"if",
"hasattr",
"(",
"entity",
",",
"\"outbou... | Build POST data for sending out to remotes.
:param entity: The outbound ready entity for this protocol.
:param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties.
:param to_user_key: (Optional) Public key of user we're sending a private payload to.
... | [
"Build",
"POST",
"data",
"for",
"sending",
"out",
"to",
"remotes",
"."
] | python | train | 51.066667 |
numberly/appnexus-client | appnexus/client.py | https://github.com/numberly/appnexus-client/blob/d6a813449ab6fd93bfbceaa937a168fa9a78b890/appnexus/client.py#L110-L129 | def update_token(self):
"""Request a new token and store it for future use"""
logger.info('updating token')
if None in self.credentials.values():
raise RuntimeError("You must provide an username and a password")
credentials = dict(auth=self.credentials)
url = self.tes... | [
"def",
"update_token",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'updating token'",
")",
"if",
"None",
"in",
"self",
".",
"credentials",
".",
"values",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"You must provide an username and a password\"",
")",... | Request a new token and store it for future use | [
"Request",
"a",
"new",
"token",
"and",
"store",
"it",
"for",
"future",
"use"
] | python | train | 44.15 |
chemlab/chemlab | chemlab/qc/pgbf.py | https://github.com/chemlab/chemlab/blob/c8730966316d101e24f39ac3b96b51282aba0abe/chemlab/qc/pgbf.py#L66-L75 | def mesh(self,xyzs):
"""
Evaluate basis function on a mesh of points *xyz*.
"""
I,J,K = self.powers
d = np.asarray(xyzs,'d')-self.origin
# Got help from stackoverflow user @unutbu with this.
# See: http://stackoverflow.com/questions/17391052/compute-square-distanc... | [
"def",
"mesh",
"(",
"self",
",",
"xyzs",
")",
":",
"I",
",",
"J",
",",
"K",
"=",
"self",
".",
"powers",
"d",
"=",
"np",
".",
"asarray",
"(",
"xyzs",
",",
"'d'",
")",
"-",
"self",
".",
"origin",
"# Got help from stackoverflow user @unutbu with this.",
"... | Evaluate basis function on a mesh of points *xyz*. | [
"Evaluate",
"basis",
"function",
"on",
"a",
"mesh",
"of",
"points",
"*",
"xyz",
"*",
"."
] | python | train | 45.2 |
mikedh/trimesh | trimesh/base.py | https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/base.py#L1700-L1750 | def compute_stable_poses(self,
center_mass=None,
sigma=0.0,
n_samples=1,
threshold=0.0):
"""
Computes stable orientations of a mesh and their quasi-static probabilites.
This metho... | [
"def",
"compute_stable_poses",
"(",
"self",
",",
"center_mass",
"=",
"None",
",",
"sigma",
"=",
"0.0",
",",
"n_samples",
"=",
"1",
",",
"threshold",
"=",
"0.0",
")",
":",
"return",
"poses",
".",
"compute_stable_poses",
"(",
"mesh",
"=",
"self",
",",
"cen... | Computes stable orientations of a mesh and their quasi-static probabilites.
This method samples the location of the center of mass from a multivariate
gaussian (mean at com, cov equal to identity times sigma) over n_samples.
For each sample, it computes the stable resting poses of the mesh on a... | [
"Computes",
"stable",
"orientations",
"of",
"a",
"mesh",
"and",
"their",
"quasi",
"-",
"static",
"probabilites",
"."
] | python | train | 43.176471 |
scikit-tda/kepler-mapper | kmapper/cover.py | https://github.com/scikit-tda/kepler-mapper/blob/d4ed39f6392b0a134dd573d7d9c4aa65fbef3a7d/kmapper/cover.py#L246-L273 | def transform(self, data, centers=None):
""" Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`.
Empty hypercubes are removed from the result
Parameters
===========
data: array-like
Data to find in ... | [
"def",
"transform",
"(",
"self",
",",
"data",
",",
"centers",
"=",
"None",
")",
":",
"centers",
"=",
"centers",
"or",
"self",
".",
"centers_",
"hypercubes",
"=",
"[",
"self",
".",
"transform_single",
"(",
"data",
",",
"cube",
",",
"i",
")",
"for",
"i... | Find entries of all hypercubes. If `centers=None`, then use `self.centers_` as computed in `self.fit`.
Empty hypercubes are removed from the result
Parameters
===========
data: array-like
Data to find in entries in cube. Warning: first column must be index ... | [
"Find",
"entries",
"of",
"all",
"hypercubes",
".",
"If",
"centers",
"=",
"None",
"then",
"use",
"self",
".",
"centers_",
"as",
"computed",
"in",
"self",
".",
"fit",
".",
"Empty",
"hypercubes",
"are",
"removed",
"from",
"the",
"result"
] | python | train | 33.928571 |
GNS3/gns3-server | gns3server/utils/asyncio/embed_shell.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/utils/asyncio/embed_shell.py#L85-L106 | def help(self, *args):
"""
Show help
"""
res = ''
if len(args) == 0:
res = 'Help:\n'
for name, value in inspect.getmembers(self):
if not inspect.isgeneratorfunction(value):
continue
if name.startswith('_') or (len(args) ... | [
"def",
"help",
"(",
"self",
",",
"*",
"args",
")",
":",
"res",
"=",
"''",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"res",
"=",
"'Help:\\n'",
"for",
"name",
",",
"value",
"in",
"inspect",
".",
"getmembers",
"(",
"self",
")",
":",
"if",
"no... | Show help | [
"Show",
"help"
] | python | train | 31.863636 |
brunato/lograptor | setup.py | https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/setup.py#L125-L133 | def _make_spec_file(self):
"""
Customize spec file inserting %config section
"""
spec_file = setuptools.command.bdist_rpm.bdist_rpm._make_spec_file(self)
spec_file.append('%config(noreplace) /etc/lograptor/lograptor.conf')
spec_file.append('%config(noreplace) /etc/lograpt... | [
"def",
"_make_spec_file",
"(",
"self",
")",
":",
"spec_file",
"=",
"setuptools",
".",
"command",
".",
"bdist_rpm",
".",
"bdist_rpm",
".",
"_make_spec_file",
"(",
"self",
")",
"spec_file",
".",
"append",
"(",
"'%config(noreplace) /etc/lograptor/lograptor.conf'",
")",... | Customize spec file inserting %config section | [
"Customize",
"spec",
"file",
"inserting",
"%config",
"section"
] | python | train | 48.333333 |
globus/globus-cli | globus_cli/commands/rename.py | https://github.com/globus/globus-cli/blob/336675ff24da64c5ee487243f39ae39fc49a7e14/globus_cli/commands/rename.py#L14-L34 | def rename_command(source, destination):
"""
Executor for `globus rename`
"""
source_ep, source_path = source
dest_ep, dest_path = destination
if source_ep != dest_ep:
raise click.UsageError(
(
"rename requires that the source and dest "
"endp... | [
"def",
"rename_command",
"(",
"source",
",",
"destination",
")",
":",
"source_ep",
",",
"source_path",
"=",
"source",
"dest_ep",
",",
"dest_path",
"=",
"destination",
"if",
"source_ep",
"!=",
"dest_ep",
":",
"raise",
"click",
".",
"UsageError",
"(",
"(",
"\"... | Executor for `globus rename` | [
"Executor",
"for",
"globus",
"rename"
] | python | train | 31.285714 |
snowblink14/smatch | smatch-table.py | https://github.com/snowblink14/smatch/blob/ad7e6553a3d52e469b2eef69d7716c87a67eedac/smatch-table.py#L201-L258 | def check_args(args):
"""
Parse arguments and check if the arguments are valid
"""
if not os.path.exists(args.fd):
print("Not a valid path", args.fd, file=ERROR_LOG)
return [], [], False
if args.fl is not None:
# we already ensure the file can be opened and opened the file
... | [
"def",
"check_args",
"(",
"args",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"args",
".",
"fd",
")",
":",
"print",
"(",
"\"Not a valid path\"",
",",
"args",
".",
"fd",
",",
"file",
"=",
"ERROR_LOG",
")",
"return",
"[",
"]",
",",
... | Parse arguments and check if the arguments are valid | [
"Parse",
"arguments",
"and",
"check",
"if",
"the",
"arguments",
"are",
"valid"
] | python | train | 36.551724 |
GNS3/gns3-server | gns3server/controller/import_project.py | https://github.com/GNS3/gns3-server/blob/a221678448fb5d24e977ef562f81d56aacc89ab1/gns3server/controller/import_project.py#L176-L187 | def _move_files_to_compute(compute, project_id, directory, files_path):
"""
Move the files to a remote compute
"""
location = os.path.join(directory, files_path)
if os.path.exists(location):
for (dirpath, dirnames, filenames) in os.walk(location):
for filename in filenames:
... | [
"def",
"_move_files_to_compute",
"(",
"compute",
",",
"project_id",
",",
"directory",
",",
"files_path",
")",
":",
"location",
"=",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"files_path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"lo... | Move the files to a remote compute | [
"Move",
"the",
"files",
"to",
"a",
"remote",
"compute"
] | python | train | 45.333333 |
chaoss/grimoirelab-manuscripts | manuscripts/metrics/gerrit.py | https://github.com/chaoss/grimoirelab-manuscripts/blob/94a3ad4f11bfbcd6c5190e01cb5d3e47a5187cd9/manuscripts/metrics/gerrit.py#L106-L121 | def __get_metrics(self):
""" Each metric must have its own filters copy to modify it freely"""
esfilters_merge = None
esfilters_abandon = None
if self.esfilters:
esfilters_merge = self.esfilters.copy()
esfilters_abandon = self.esfilters.copy()
merged = Me... | [
"def",
"__get_metrics",
"(",
"self",
")",
":",
"esfilters_merge",
"=",
"None",
"esfilters_abandon",
"=",
"None",
"if",
"self",
".",
"esfilters",
":",
"esfilters_merge",
"=",
"self",
".",
"esfilters",
".",
"copy",
"(",
")",
"esfilters_abandon",
"=",
"self",
"... | Each metric must have its own filters copy to modify it freely | [
"Each",
"metric",
"must",
"have",
"its",
"own",
"filters",
"copy",
"to",
"modify",
"it",
"freely"
] | python | train | 44.1875 |
inasafe/inasafe | safe/report/extractors/analysis_provenance_details.py | https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/report/extractors/analysis_provenance_details.py#L498-L525 | def sorted_keywords_by_order(keywords, order):
"""Sort keywords based on defined order.
:param keywords: Keyword to be sorted.
:type keywords: dict
:param order: Ordered list of key.
:type order: list
:return: Ordered dictionary based on order list.
:rtype: OrderedDict
"""
# we n... | [
"def",
"sorted_keywords_by_order",
"(",
"keywords",
",",
"order",
")",
":",
"# we need to delete item with no value",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"keywords",
".",
"items",
"(",
")",
")",
":",
"if",
"value",
"is",
"None",
":",
"del",
"keywo... | Sort keywords based on defined order.
:param keywords: Keyword to be sorted.
:type keywords: dict
:param order: Ordered list of key.
:type order: list
:return: Ordered dictionary based on order list.
:rtype: OrderedDict | [
"Sort",
"keywords",
"based",
"on",
"defined",
"order",
"."
] | python | train | 26.285714 |
andreikop/qutepart | qutepart/__init__.py | https://github.com/andreikop/qutepart/blob/109d76b239751318bcef06f39b2fbbf18687a40b/qutepart/__init__.py#L744-L783 | def detectSyntax(self,
xmlFileName=None,
mimeType=None,
language=None,
sourceFilePath=None,
firstLine=None):
"""Get syntax by next parameters (fill as many, as known):
* name of XML file with sy... | [
"def",
"detectSyntax",
"(",
"self",
",",
"xmlFileName",
"=",
"None",
",",
"mimeType",
"=",
"None",
",",
"language",
"=",
"None",
",",
"sourceFilePath",
"=",
"None",
",",
"firstLine",
"=",
"None",
")",
":",
"oldLanguage",
"=",
"self",
".",
"language",
"("... | Get syntax by next parameters (fill as many, as known):
* name of XML file with syntax definition
* MIME type of source file
* Programming language name
* Source file path
* First line of source file
First parameter in the list has the hightest prior... | [
"Get",
"syntax",
"by",
"next",
"parameters",
"(",
"fill",
"as",
"many",
"as",
"known",
")",
":"
] | python | train | 39.125 |
Kortemme-Lab/klab | klab/bio/pdb.py | https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdb.py#L597-L615 | def retrieve(pdb_id, cache_dir = None, strict = True, parse_ligands = False):
'''Creates a PDB object by using a cached copy of the file if it exists or by retrieving the file from the RCSB.'''
# Check to see whether we have a cached copy
pdb_id = pdb_id.upper()
if cache_dir:
... | [
"def",
"retrieve",
"(",
"pdb_id",
",",
"cache_dir",
"=",
"None",
",",
"strict",
"=",
"True",
",",
"parse_ligands",
"=",
"False",
")",
":",
"# Check to see whether we have a cached copy",
"pdb_id",
"=",
"pdb_id",
".",
"upper",
"(",
")",
"if",
"cache_dir",
":",
... | Creates a PDB object by using a cached copy of the file if it exists or by retrieving the file from the RCSB. | [
"Creates",
"a",
"PDB",
"object",
"by",
"using",
"a",
"cached",
"copy",
"of",
"the",
"file",
"if",
"it",
"exists",
"or",
"by",
"retrieving",
"the",
"file",
"from",
"the",
"RCSB",
"."
] | python | train | 43.526316 |
StackStorm/pybind | pybind/slxos/v17s_1_02/protocol/spanning_tree/rpvst/__init__.py | https://github.com/StackStorm/pybind/blob/44c467e71b2b425be63867aba6e6fa28b2cfe7fb/pybind/slxos/v17s_1_02/protocol/spanning_tree/rpvst/__init__.py#L284-L305 | def _set_port_channel(self, v, load=False):
"""
Setter method for port_channel, mapped from YANG variable /protocol/spanning_tree/rpvst/port_channel (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_channel is considered as a private
method. Backends l... | [
"def",
"_set_port_channel",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | Setter method for port_channel, mapped from YANG variable /protocol/spanning_tree/rpvst/port_channel (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_channel is considered as a private
method. Backends looking to populate this variable should
do so via ca... | [
"Setter",
"method",
"for",
"port_channel",
"mapped",
"from",
"YANG",
"variable",
"/",
"protocol",
"/",
"spanning_tree",
"/",
"rpvst",
"/",
"port_channel",
"(",
"container",
")",
"If",
"this",
"variable",
"is",
"read",
"-",
"only",
"(",
"config",
":",
"false"... | python | train | 79.318182 |
rwl/godot | godot/parsing_util.py | https://github.com/rwl/godot/blob/013687c9e8983d2aa2ceebb8a76c5c4f1e37c90f/godot/parsing_util.py#L255-L273 | def nsplit(seq, n=2):
""" Split a sequence into pieces of length n
If the length of the sequence isn't a multiple of n, the rest is discarded.
Note that nsplit will split strings into individual characters.
Examples:
>>> nsplit("aabbcc")
[("a", "a"), ("b", "b"), ("c", "c")]
>>> nsplit("aab... | [
"def",
"nsplit",
"(",
"seq",
",",
"n",
"=",
"2",
")",
":",
"return",
"[",
"xy",
"for",
"xy",
"in",
"itertools",
".",
"izip",
"(",
"*",
"[",
"iter",
"(",
"seq",
")",
"]",
"*",
"n",
")",
"]"
] | Split a sequence into pieces of length n
If the length of the sequence isn't a multiple of n, the rest is discarded.
Note that nsplit will split strings into individual characters.
Examples:
>>> nsplit("aabbcc")
[("a", "a"), ("b", "b"), ("c", "c")]
>>> nsplit("aabbcc",n=3)
[("a", "a", "b")... | [
"Split",
"a",
"sequence",
"into",
"pieces",
"of",
"length",
"n"
] | python | test | 26.631579 |
apache/incubator-mxnet | tools/caffe_converter/compare_layers.py | https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/tools/caffe_converter/compare_layers.py#L83-L146 | def convert_and_compare_caffe_to_mxnet(image_url, gpu, caffe_prototxt_path, caffe_model_path,
caffe_mean, mean_diff_allowed, max_diff_allowed):
"""
Run the layer comparison on a caffe model, given its prototxt, weights and mean.
The comparison is done by inferring on a... | [
"def",
"convert_and_compare_caffe_to_mxnet",
"(",
"image_url",
",",
"gpu",
",",
"caffe_prototxt_path",
",",
"caffe_model_path",
",",
"caffe_mean",
",",
"mean_diff_allowed",
",",
"max_diff_allowed",
")",
":",
"import",
"caffe",
"from",
"caffe_proto_utils",
"import",
"rea... | Run the layer comparison on a caffe model, given its prototxt, weights and mean.
The comparison is done by inferring on a given image using both caffe and mxnet model
:param image_url: image file or url to run inference on
:param gpu: gpu to use, -1 for cpu
:param caffe_prototxt_path: path to caffe prot... | [
"Run",
"the",
"layer",
"comparison",
"on",
"a",
"caffe",
"model",
"given",
"its",
"prototxt",
"weights",
"and",
"mean",
".",
"The",
"comparison",
"is",
"done",
"by",
"inferring",
"on",
"a",
"given",
"image",
"using",
"both",
"caffe",
"and",
"mxnet",
"model... | python | train | 39.0625 |
SHDShim/pytheos | pytheos/eqn_therm_Speziale.py | https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_therm_Speziale.py#L15-L30 | def speziale_grun(v, v0, gamma0, q0, q1):
"""
calculate Gruneisen parameter for the Speziale equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1:... | [
"def",
"speziale_grun",
"(",
"v",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
")",
":",
"if",
"isuncertainties",
"(",
"[",
"v",
",",
"v0",
",",
"gamma0",
",",
"q0",
",",
"q1",
"]",
")",
":",
"gamma",
"=",
"gamma0",
"*",
"unp",
".",
"exp",
... | calculate Gruneisen parameter for the Speziale equation
:param v: unit-cell volume in A^3
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen parameter at 1 bar
:param q0: logarithmic derivative of Gruneisen parameter
:param q1: logarithmic derivative of Gruneisen parameter
:re... | [
"calculate",
"Gruneisen",
"parameter",
"for",
"the",
"Speziale",
"equation"
] | python | train | 37.4375 |
ihgazni2/elist | elist/elist.py | https://github.com/ihgazni2/elist/blob/8c07b5029bda34ead60ce10335ceb145f209263c/elist/elist.py#L1440-L1498 | def insert_many(ol,eles,locs,**kwargs):
'''
from elist.elist import *
ol = [1,2,3,4,5]
eles = [7,77,777]
locs = [0,2,4]
id(ol)
new = insert_many(ol,eles,locs)
ol
new
id(new)
####
ol = [1,2,3,4,5]
eles = [7,77,777]
... | [
"def",
"insert_many",
"(",
"ol",
",",
"eles",
",",
"locs",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"'mode'",
"in",
"kwargs",
")",
":",
"mode",
"=",
"kwargs",
"[",
"\"mode\"",
"]",
"else",
":",
"mode",
"=",
"\"new\"",
"eles",
"=",
"copy",
".... | from elist.elist import *
ol = [1,2,3,4,5]
eles = [7,77,777]
locs = [0,2,4]
id(ol)
new = insert_many(ol,eles,locs)
ol
new
id(new)
####
ol = [1,2,3,4,5]
eles = [7,77,777]
locs = [0,2,4]
id(ol)
rslt = insert_ma... | [
"from",
"elist",
".",
"elist",
"import",
"*",
"ol",
"=",
"[",
"1",
"2",
"3",
"4",
"5",
"]",
"eles",
"=",
"[",
"7",
"77",
"777",
"]",
"locs",
"=",
"[",
"0",
"2",
"4",
"]",
"id",
"(",
"ol",
")",
"new",
"=",
"insert_many",
"(",
"ol",
"eles",
... | python | valid | 22.79661 |
kontron/python-aardvark | pyaardvark/aardvark.py | https://github.com/kontron/python-aardvark/blob/9827f669fbdc5bceb98e7d08a294b4e4e455d0d5/pyaardvark/aardvark.py#L303-L309 | def enable_spi(self):
"""Set this to `True` to enable the hardware SPI interface. If set to
`False` the hardware interface will be disabled and its pins (MISO,
MOSI, SCK and SS) can be used as GPIOs.
"""
config = self._interface_configuration(CONFIG_QUERY)
return config =... | [
"def",
"enable_spi",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"_interface_configuration",
"(",
"CONFIG_QUERY",
")",
"return",
"config",
"==",
"CONFIG_SPI_GPIO",
"or",
"config",
"==",
"CONFIG_SPI_I2C"
] | Set this to `True` to enable the hardware SPI interface. If set to
`False` the hardware interface will be disabled and its pins (MISO,
MOSI, SCK and SS) can be used as GPIOs. | [
"Set",
"this",
"to",
"True",
"to",
"enable",
"the",
"hardware",
"SPI",
"interface",
".",
"If",
"set",
"to",
"False",
"the",
"hardware",
"interface",
"will",
"be",
"disabled",
"and",
"its",
"pins",
"(",
"MISO",
"MOSI",
"SCK",
"and",
"SS",
")",
"can",
"b... | python | train | 51.285714 |
cablehead/vanilla | vanilla/core.py | https://github.com/cablehead/vanilla/blob/c9f5b86f45720a30e8840fb68b1429b919c4ca66/vanilla/core.py#L243-L249 | def state(self, state=vanilla.message.NoState):
"""
Returns a `State`_ `Pair`_.
*state* if supplied sets the intial state.
"""
return vanilla.message.State(self, state=state) | [
"def",
"state",
"(",
"self",
",",
"state",
"=",
"vanilla",
".",
"message",
".",
"NoState",
")",
":",
"return",
"vanilla",
".",
"message",
".",
"State",
"(",
"self",
",",
"state",
"=",
"state",
")"
] | Returns a `State`_ `Pair`_.
*state* if supplied sets the intial state. | [
"Returns",
"a",
"State",
"_",
"Pair",
"_",
"."
] | python | train | 29.857143 |
pytroll/satpy | satpy/multiscene.py | https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/multiscene.py#L246-L248 | def load(self, *args, **kwargs):
"""Load the required datasets from the multiple scenes."""
self._generate_scene_func(self._scenes, 'load', False, *args, **kwargs) | [
"def",
"load",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_generate_scene_func",
"(",
"self",
".",
"_scenes",
",",
"'load'",
",",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Load the required datasets from the multiple scenes. | [
"Load",
"the",
"required",
"datasets",
"from",
"the",
"multiple",
"scenes",
"."
] | python | train | 59 |
attm2x/m2x-python | m2x/v2/collections.py | https://github.com/attm2x/m2x-python/blob/df83f590114692b1f96577148b7ba260065905bb/m2x/v2/collections.py#L28-L37 | def add_device(self, device_id):
""" Method for `Add device to collection <https://m2x.att.com/developer/documentation/v2/collections#Add-device-to-collection>`_ endpoint.
:param device_id: ID of the Device being added to Collection
:type device_id: str
:raises: :class:`~requests.excep... | [
"def",
"add_device",
"(",
"self",
",",
"device_id",
")",
":",
"path",
"=",
"self",
".",
"subpath",
"(",
"'/devices/{device_id}'",
".",
"format",
"(",
"device_id",
"=",
"device_id",
")",
")",
"return",
"self",
".",
"api",
".",
"put",
"(",
"path",
")"
] | Method for `Add device to collection <https://m2x.att.com/developer/documentation/v2/collections#Add-device-to-collection>`_ endpoint.
:param device_id: ID of the Device being added to Collection
:type device_id: str
:raises: :class:`~requests.exceptions.HTTPError` if an error occurs when send... | [
"Method",
"for",
"Add",
"device",
"to",
"collection",
"<https",
":",
"//",
"m2x",
".",
"att",
".",
"com",
"/",
"developer",
"/",
"documentation",
"/",
"v2",
"/",
"collections#Add",
"-",
"device",
"-",
"to",
"-",
"collection",
">",
"_",
"endpoint",
"."
] | python | test | 50.2 |
tornadoweb/tornado | tornado/web.py | https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/web.py#L777-L789 | def get_secure_cookie_key_version(
self, name: str, value: str = None
) -> Optional[int]:
"""Returns the signing key version of the secure cookie.
The version is returned as int.
"""
self.require_setting("cookie_secret", "secure cookies")
if value is None:
... | [
"def",
"get_secure_cookie_key_version",
"(",
"self",
",",
"name",
":",
"str",
",",
"value",
":",
"str",
"=",
"None",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"self",
".",
"require_setting",
"(",
"\"cookie_secret\"",
",",
"\"secure cookies\"",
")",
"if",
... | Returns the signing key version of the secure cookie.
The version is returned as int. | [
"Returns",
"the",
"signing",
"key",
"version",
"of",
"the",
"secure",
"cookie",
"."
] | python | train | 33.615385 |
gwastro/pycbc-glue | pycbc_glue/pipeline.py | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L2156-L2182 | def write_script(self):
"""
Write the workflow to a script (.sh instead of .dag).
Assuming that parents were added to the DAG before their children,
dependencies should be handled correctly.
"""
if not self.__dag_file_path:
raise CondorDAGError, "No path for DAG file"
try:
dfp =... | [
"def",
"write_script",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__dag_file_path",
":",
"raise",
"CondorDAGError",
",",
"\"No path for DAG file\"",
"try",
":",
"dfp",
"=",
"self",
".",
"__dag_file_path",
"outfilename",
"=",
"\".\"",
".",
"join",
"(",
... | Write the workflow to a script (.sh instead of .dag).
Assuming that parents were added to the DAG before their children,
dependencies should be handled correctly. | [
"Write",
"the",
"workflow",
"to",
"a",
"script",
"(",
".",
"sh",
"instead",
"of",
".",
"dag",
")",
"."
] | python | train | 35.148148 |
XML-Security/signxml | signxml/util/__init__.py | https://github.com/XML-Security/signxml/blob/16503242617e9b25e5c2c9ced5ef18a06ffde146/signxml/util/__init__.py#L64-L93 | def long_to_bytes(n, blocksize=0):
"""long_to_bytes(n:long, blocksize:int) : string
Convert a long integer to a byte string.
If optional blocksize is given and greater than zero, pad the front of the
byte string with binary zeros so that the length is a multiple of
blocksize.
"""
# after mu... | [
"def",
"long_to_bytes",
"(",
"n",
",",
"blocksize",
"=",
"0",
")",
":",
"# after much testing, this algorithm was deemed to be the fastest",
"s",
"=",
"b''",
"if",
"USING_PYTHON2",
":",
"n",
"=",
"long",
"(",
"n",
")",
"# noqa",
"pack",
"=",
"struct",
".",
"pa... | long_to_bytes(n:long, blocksize:int) : string
Convert a long integer to a byte string.
If optional blocksize is given and greater than zero, pad the front of the
byte string with binary zeros so that the length is a multiple of
blocksize. | [
"long_to_bytes",
"(",
"n",
":",
"long",
"blocksize",
":",
"int",
")",
":",
"string",
"Convert",
"a",
"long",
"integer",
"to",
"a",
"byte",
"string",
"."
] | python | train | 31.833333 |
atl/py-smartdc | smartdc/machine.py | https://github.com/atl/py-smartdc/blob/cc5cd5910e19004cc46e376ce035affe28fc798e/smartdc/machine.py#L403-L422 | def delete_metadata_at_key(self, key):
"""
::
DELETE /:login/machines/:id/metadata/:key
:param key: identifier for matadata entry
:type key: :py:class:`basestring`
:Returns: current metadata
:rtype: :py:class:`dict`
... | [
"def",
"delete_metadata_at_key",
"(",
"self",
",",
"key",
")",
":",
"j",
",",
"r",
"=",
"self",
".",
"datacenter",
".",
"request",
"(",
"'DELETE'",
",",
"self",
".",
"path",
"+",
"'/metadata/'",
"+",
"key",
")",
"r",
".",
"raise_for_status",
"(",
")",
... | ::
DELETE /:login/machines/:id/metadata/:key
:param key: identifier for matadata entry
:type key: :py:class:`basestring`
:Returns: current metadata
:rtype: :py:class:`dict`
Deletes the machine metadata contained at 'key'. Also expli... | [
"::",
"DELETE",
"/",
":",
"login",
"/",
"machines",
"/",
":",
"id",
"/",
"metadata",
"/",
":",
"key",
":",
"param",
"key",
":",
"identifier",
"for",
"matadata",
"entry",
":",
"type",
"key",
":",
":",
"py",
":",
"class",
":",
"basestring",
":",
"Ret... | python | train | 32.3 |
salesking/salesking_python_sdk | salesking/resources.py | https://github.com/salesking/salesking_python_sdk/blob/0d5a95c5ee4e16a85562ceaf67bb11b55e47ee4c/salesking/resources.py#L165-L173 | def to_json(self):
"""
put the object to json and remove the internal stuff
salesking schema stores the type in the title
"""
data = json.dumps(self)
out = u'{"%s":%s}' % (self.schema['title'], data)
return out | [
"def",
"to_json",
"(",
"self",
")",
":",
"data",
"=",
"json",
".",
"dumps",
"(",
"self",
")",
"out",
"=",
"u'{\"%s\":%s}'",
"%",
"(",
"self",
".",
"schema",
"[",
"'title'",
"]",
",",
"data",
")",
"return",
"out"
] | put the object to json and remove the internal stuff
salesking schema stores the type in the title | [
"put",
"the",
"object",
"to",
"json",
"and",
"remove",
"the",
"internal",
"stuff",
"salesking",
"schema",
"stores",
"the",
"type",
"in",
"the",
"title"
] | python | train | 28.777778 |
keon/algorithms | algorithms/sort/insertion_sort.py | https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/insertion_sort.py#L1-L25 | def insertion_sort(arr, simulation=False):
""" Insertion Sort
Complexity: O(n^2)
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
for i in range(len(arr)):
cursor = arr[i]
pos = i
while pos > 0 and arr[pos - 1] > cu... | [
"def",
"insertion_sort",
"(",
"arr",
",",
"simulation",
"=",
"False",
")",
":",
"iteration",
"=",
"0",
"if",
"simulation",
":",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"for",
"i",
"in",
"range",
"(",
"len",
... | Insertion Sort
Complexity: O(n^2) | [
"Insertion",
"Sort",
"Complexity",
":",
"O",
"(",
"n^2",
")"
] | python | train | 24.6 |
achiku/jungle | jungle/ec2.py | https://github.com/achiku/jungle/blob/fb63f845cfa9e9c0dfbabd8cfa3ebca8177a11ca/jungle/ec2.py#L35-L40 | def _get_max_name_len(instances):
"""get max length of Tag:Name"""
# FIXME: ec2.instanceCollection doesn't have __len__
for i in instances:
return max([len(get_tag_value(i.tags, 'Name')) for i in instances])
return 0 | [
"def",
"_get_max_name_len",
"(",
"instances",
")",
":",
"# FIXME: ec2.instanceCollection doesn't have __len__",
"for",
"i",
"in",
"instances",
":",
"return",
"max",
"(",
"[",
"len",
"(",
"get_tag_value",
"(",
"i",
".",
"tags",
",",
"'Name'",
")",
")",
"for",
"... | get max length of Tag:Name | [
"get",
"max",
"length",
"of",
"Tag",
":",
"Name"
] | python | train | 39.166667 |
Dentosal/python-sc2 | sc2/position.py | https://github.com/Dentosal/python-sc2/blob/608bd25f04e89d39cef68b40101d8e9a8a7f1634/sc2/position.py#L183-L205 | def circle_intersection(self, p: "Point2", r: Union[int, float]) -> Set["Point2"]:
""" self is point1, p is point2, r is the radius for circles originating in both points
Used in ramp finding """
assert self != p
distanceBetweenPoints = self.distance_to(p)
assert r > distanceBetw... | [
"def",
"circle_intersection",
"(",
"self",
",",
"p",
":",
"\"Point2\"",
",",
"r",
":",
"Union",
"[",
"int",
",",
"float",
"]",
")",
"->",
"Set",
"[",
"\"Point2\"",
"]",
":",
"assert",
"self",
"!=",
"p",
"distanceBetweenPoints",
"=",
"self",
".",
"dista... | self is point1, p is point2, r is the radius for circles originating in both points
Used in ramp finding | [
"self",
"is",
"point1",
"p",
"is",
"point2",
"r",
"is",
"the",
"radius",
"for",
"circles",
"originating",
"in",
"both",
"points",
"Used",
"in",
"ramp",
"finding"
] | python | train | 56.695652 |
biocore/burrito-fillings | bfillings/blat.py | https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/blat.py#L349-L422 | def assign_dna_reads_to_protein_database(query_fasta_fp, database_fasta_fp,
output_fp, temp_dir="/tmp", params=None):
"""Assign DNA reads to a database fasta of protein sequences.
Wraps assign_reads_to_database, setting database and query types. All
parameters are s... | [
"def",
"assign_dna_reads_to_protein_database",
"(",
"query_fasta_fp",
",",
"database_fasta_fp",
",",
"output_fp",
",",
"temp_dir",
"=",
"\"/tmp\"",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"my_params",
"... | Assign DNA reads to a database fasta of protein sequences.
Wraps assign_reads_to_database, setting database and query types. All
parameters are set to default unless params is passed. A temporary
file must be written containing the translated sequences from the input
query fasta file because BLAT canno... | [
"Assign",
"DNA",
"reads",
"to",
"a",
"database",
"fasta",
"of",
"protein",
"sequences",
"."
] | python | train | 40.797297 |
mattupstate/flask-social | flask_social/views.py | https://github.com/mattupstate/flask-social/blob/36f5790c8fb6d4d9a5120d099419ba30fd73e897/flask_social/views.py#L44-L50 | def login(provider_id):
"""Starts the provider login OAuth flow"""
provider = get_provider_or_404(provider_id)
callback_url = get_authorize_callback('login', provider_id)
post_login = request.form.get('next', get_post_login_redirect())
session[config_value('POST_OAUTH_LOGIN_SESSION_KEY')] = post_log... | [
"def",
"login",
"(",
"provider_id",
")",
":",
"provider",
"=",
"get_provider_or_404",
"(",
"provider_id",
")",
"callback_url",
"=",
"get_authorize_callback",
"(",
"'login'",
",",
"provider_id",
")",
"post_login",
"=",
"request",
".",
"form",
".",
"get",
"(",
"... | Starts the provider login OAuth flow | [
"Starts",
"the",
"provider",
"login",
"OAuth",
"flow"
] | python | train | 51.428571 |
asmodehn/filefinder2 | filefinder2/util.py | https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/util.py#L111-L125 | def set_package(fxn):
"""Set __package__ on the returned module.
This function is deprecated.
"""
@functools.wraps(fxn)
def set_package_wrapper(*args, **kwargs):
warnings.warn('The import system now takes care of this automatically.',
DeprecationWarning, stacklevel=2)
... | [
"def",
"set_package",
"(",
"fxn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fxn",
")",
"def",
"set_package_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"'The import system now takes care of this automatical... | Set __package__ on the returned module.
This function is deprecated. | [
"Set",
"__package__",
"on",
"the",
"returned",
"module",
".",
"This",
"function",
"is",
"deprecated",
"."
] | python | train | 41.6 |
tensorflow/probability | tensorflow_probability/python/edward2/random_variable.py | https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L160-L170 | def value(self):
"""Get tensor that the random variable corresponds to."""
if self._value is None:
try:
self._value = self.distribution.sample(self.sample_shape_tensor())
except NotImplementedError:
raise NotImplementedError(
"sample is not implemented for {0}. You must e... | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_value",
"is",
"None",
":",
"try",
":",
"self",
".",
"_value",
"=",
"self",
".",
"distribution",
".",
"sample",
"(",
"self",
".",
"sample_shape_tensor",
"(",
")",
")",
"except",
"NotImplemented... | Get tensor that the random variable corresponds to. | [
"Get",
"tensor",
"that",
"the",
"random",
"variable",
"corresponds",
"to",
"."
] | python | test | 42.636364 |
psd-tools/psd-tools | src/psd_tools/api/pil_io.py | https://github.com/psd-tools/psd-tools/blob/4952b57bcf1cf2c1f16fd9d6d51d4fa0b53bce4e/src/psd_tools/api/pil_io.py#L22-L32 | def get_pil_mode(value, alpha=False):
"""Get PIL mode from ColorMode."""
name = {
'GRAYSCALE': 'L',
'BITMAP': '1',
'DUOTONE': 'L',
'INDEXED': 'P',
}.get(value, value)
if alpha and name in ('L', 'RGB'):
name += 'A'
return name | [
"def",
"get_pil_mode",
"(",
"value",
",",
"alpha",
"=",
"False",
")",
":",
"name",
"=",
"{",
"'GRAYSCALE'",
":",
"'L'",
",",
"'BITMAP'",
":",
"'1'",
",",
"'DUOTONE'",
":",
"'L'",
",",
"'INDEXED'",
":",
"'P'",
",",
"}",
".",
"get",
"(",
"value",
","... | Get PIL mode from ColorMode. | [
"Get",
"PIL",
"mode",
"from",
"ColorMode",
"."
] | python | train | 25 |
sony/nnabla | python/src/nnabla/utils/converter/onnx/importer.py | https://github.com/sony/nnabla/blob/aaf3d33b7cbb38f2a03aa754178ba8f7c8481320/python/src/nnabla/utils/converter/onnx/importer.py#L353-L359 | def rearrange_pads(pads):
""" Interleave pad values to match NNabla format
(S0,S1,E0,E1) => (S0,E0,S1,E1)"""
half = len(pads)//2
starts = pads[:half]
ends = pads[half:]
return [j for i in zip(starts, ends) for j in i] | [
"def",
"rearrange_pads",
"(",
"pads",
")",
":",
"half",
"=",
"len",
"(",
"pads",
")",
"//",
"2",
"starts",
"=",
"pads",
"[",
":",
"half",
"]",
"ends",
"=",
"pads",
"[",
"half",
":",
"]",
"return",
"[",
"j",
"for",
"i",
"in",
"zip",
"(",
"starts... | Interleave pad values to match NNabla format
(S0,S1,E0,E1) => (S0,E0,S1,E1) | [
"Interleave",
"pad",
"values",
"to",
"match",
"NNabla",
"format",
"(",
"S0",
"S1",
"E0",
"E1",
")",
"=",
">",
"(",
"S0",
"E0",
"S1",
"E1",
")"
] | python | train | 33.571429 |
cga-harvard/Hypermap-Registry | hypermap/search_api/views.py | https://github.com/cga-harvard/Hypermap-Registry/blob/899a5385b15af7fba190ab4fae1d41e47d155a1b/hypermap/search_api/views.py#L32-L361 | def elasticsearch(serializer, catalog):
"""
https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html
:param serializer:
:return:
"""
search_engine_endpoint = "{0}/{1}/_search".format(SEARCH_URL, catalog.slug)
q_text = serializer.validated_data.get("q_text")
... | [
"def",
"elasticsearch",
"(",
"serializer",
",",
"catalog",
")",
":",
"search_engine_endpoint",
"=",
"\"{0}/{1}/_search\"",
".",
"format",
"(",
"SEARCH_URL",
",",
"catalog",
".",
"slug",
")",
"q_text",
"=",
"serializer",
".",
"validated_data",
".",
"get",
"(",
... | https://www.elastic.co/guide/en/elasticsearch/reference/current/_the_search_api.html
:param serializer:
:return: | [
"https",
":",
"//",
"www",
".",
"elastic",
".",
"co",
"/",
"guide",
"/",
"en",
"/",
"elasticsearch",
"/",
"reference",
"/",
"current",
"/",
"_the_search_api",
".",
"html",
":",
"param",
"serializer",
":",
":",
"return",
":"
] | python | train | 32.748485 |
MartinHjelmare/leicacam | leicacam/cam.py | https://github.com/MartinHjelmare/leicacam/blob/1df37bccd34884737d3b5e169fae71dd2f21f1e2/leicacam/cam.py#L193-L220 | def send(self, commands):
"""Send commands to LASAF through CAM-socket.
Parameters
----------
commands : list of tuples or bytes string
Commands as a list of tuples or a bytes string. cam.prefix is
allways prepended before sending.
Returns
------... | [
"def",
"send",
"(",
"self",
",",
"commands",
")",
":",
"self",
".",
"flush",
"(",
")",
"# discard any waiting messages",
"msg",
"=",
"self",
".",
"_prepare_send",
"(",
"commands",
")",
"return",
"self",
".",
"socket",
".",
"send",
"(",
"msg",
")"
] | Send commands to LASAF through CAM-socket.
Parameters
----------
commands : list of tuples or bytes string
Commands as a list of tuples or a bytes string. cam.prefix is
allways prepended before sending.
Returns
-------
int
Bytes sent.... | [
"Send",
"commands",
"to",
"LASAF",
"through",
"CAM",
"-",
"socket",
"."
] | python | test | 25.714286 |
mitsei/dlkit | dlkit/json_/osid/markers.py | https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/osid/markers.py#L431-L444 | def get_provider(self):
"""Gets the ``Resource`` representing the provider.
return: (osid.resource.Resource) - the provider
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.*
"""
if 'providerId' not in self._... | [
"def",
"get_provider",
"(",
"self",
")",
":",
"if",
"'providerId'",
"not",
"in",
"self",
".",
"_my_map",
"or",
"not",
"self",
".",
"_my_map",
"[",
"'providerId'",
"]",
":",
"raise",
"errors",
".",
"IllegalState",
"(",
"'this sourceable object has no provider set... | Gets the ``Resource`` representing the provider.
return: (osid.resource.Resource) - the provider
raise: OperationFailed - unable to complete request
*compliance: mandatory -- This method must be implemented.* | [
"Gets",
"the",
"Resource",
"representing",
"the",
"provider",
"."
] | python | train | 48.857143 |
jepegit/cellpy | cellpy/readers/cellreader.py | https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/readers/cellreader.py#L4164-L4198 | def cell(filename=None, mass=None, instrument=None, logging_mode="INFO",
cycle_mode=None, auto_summary=True):
"""Create a CellpyData object"""
from cellpy import log
log.setup_logging(default_level=logging_mode)
cellpy_instance = setup_cellpy_instance()
if instrument is not None:
... | [
"def",
"cell",
"(",
"filename",
"=",
"None",
",",
"mass",
"=",
"None",
",",
"instrument",
"=",
"None",
",",
"logging_mode",
"=",
"\"INFO\"",
",",
"cycle_mode",
"=",
"None",
",",
"auto_summary",
"=",
"True",
")",
":",
"from",
"cellpy",
"import",
"log",
... | Create a CellpyData object | [
"Create",
"a",
"CellpyData",
"object"
] | python | train | 34.457143 |
DataONEorg/d1_python | client_onedrive/src/d1_onedrive/impl/drivers/dokan/dokan.py | https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_onedrive/src/d1_onedrive/impl/drivers/dokan/dokan.py#L524-L539 | def lockFile(self, fileName, byteOffset, length, dokanFileInfo):
"""Lock a file.
:param fileName: name of file to lock
:type fileName: ctypes.c_wchar_p
:param byteOffset: location to start lock
:type byteOffset: ctypes.c_longlong
:param length: number of bytes to lock
... | [
"def",
"lockFile",
"(",
"self",
",",
"fileName",
",",
"byteOffset",
",",
"length",
",",
"dokanFileInfo",
")",
":",
"return",
"self",
".",
"operations",
"(",
"'lockFile'",
",",
"fileName",
",",
"byteOffset",
",",
"length",
")"
] | Lock a file.
:param fileName: name of file to lock
:type fileName: ctypes.c_wchar_p
:param byteOffset: location to start lock
:type byteOffset: ctypes.c_longlong
:param length: number of bytes to lock
:type length: ctypes.c_longlong
:param dokanFileInfo: used by ... | [
"Lock",
"a",
"file",
"."
] | python | train | 35.9375 |
saltstack/salt | salt/modules/junos.py | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/junos.py#L1193-L1214 | def unlock():
'''
Unlocks the candidate configuration.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.unlock
'''
conn = __proxy__['junos.conn']()
ret = {}
ret['out'] = True
try:
conn.cu.unlock()
ret['message'] = "Successfully unlocked the config... | [
"def",
"unlock",
"(",
")",
":",
"conn",
"=",
"__proxy__",
"[",
"'junos.conn'",
"]",
"(",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'out'",
"]",
"=",
"True",
"try",
":",
"conn",
".",
"cu",
".",
"unlock",
"(",
")",
"ret",
"[",
"'message'",
"]",
"="... | Unlocks the candidate configuration.
CLI Example:
.. code-block:: bash
salt 'device_name' junos.unlock | [
"Unlocks",
"the",
"candidate",
"configuration",
"."
] | python | train | 23.363636 |
kevinpt/hdlparse | hdlparse/vhdl_parser.py | https://github.com/kevinpt/hdlparse/blob/be7cdab08a8c18815cc4504003ce9ca7fff41022/hdlparse/vhdl_parser.py#L621-L633 | def is_array(self, data_type):
'''Check if a type is a known array type
Args:
data_type (str): Name of type to check
Returns:
True if ``data_type`` is a known array type.
'''
# Split off any brackets
data_type = data_type.split('[')[0].strip()
return data_type.lower() in s... | [
"def",
"is_array",
"(",
"self",
",",
"data_type",
")",
":",
"# Split off any brackets",
"data_type",
"=",
"data_type",
".",
"split",
"(",
"'['",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"return",
"data_type",
".",
"lower",
"(",
")",
"in",
"self",
".... | Check if a type is a known array type
Args:
data_type (str): Name of type to check
Returns:
True if ``data_type`` is a known array type. | [
"Check",
"if",
"a",
"type",
"is",
"a",
"known",
"array",
"type",
"Args",
":",
"data_type",
"(",
"str",
")",
":",
"Name",
"of",
"type",
"to",
"check",
"Returns",
":",
"True",
"if",
"data_type",
"is",
"a",
"known",
"array",
"type",
"."
] | python | train | 24.846154 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.