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
pjuren/pyokit
src/pyokit/datastruct/genomicInterval.py
https://github.com/pjuren/pyokit/blob/fddae123b5d817daa39496183f19c000d9c3791f/src/pyokit/datastruct/genomicInterval.py#L57-L84
def jaccardIndex(s1, s2, stranded=False): """ Compute the Jaccard index for two collections of genomic intervals :param s1: the first set of genomic intervals :param s2: the second set of genomic intervals :param stranded: if True, treat regions on different strands as not intersecting eac...
[ "def", "jaccardIndex", "(", "s1", ",", "s2", ",", "stranded", "=", "False", ")", ":", "def", "count", "(", "s", ")", ":", "\"\"\" sum the size of regions in s. \"\"\"", "tot", "=", "0", "for", "r", "in", "s", ":", "tot", "+=", "len", "(", "r", ")", "...
Compute the Jaccard index for two collections of genomic intervals :param s1: the first set of genomic intervals :param s2: the second set of genomic intervals :param stranded: if True, treat regions on different strands as not intersecting each other, even if they occupy the same ...
[ "Compute", "the", "Jaccard", "index", "for", "two", "collections", "of", "genomic", "intervals" ]
python
train
30.714286
edeposit/marcxml2mods
src/marcxml2mods/transformators.py
https://github.com/edeposit/marcxml2mods/blob/7b44157e859b4d2a372f79598ddbf77e43d39812/src/marcxml2mods/transformators.py#L83-L109
def transform_to_mods_multimono(marc_xml, uuid, url): """ Convert `marc_xml` to multimonograph MODS data format. Args: marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. uuid (str): UUID string giving the package ID. url (str): URL...
[ "def", "transform_to_mods_multimono", "(", "marc_xml", ",", "uuid", ",", "url", ")", ":", "marc_xml", "=", "_read_content_or_path", "(", "marc_xml", ")", "transformed", "=", "xslt_transformation", "(", "marc_xml", ",", "_absolute_template_path", "(", "\"MARC21toMultiM...
Convert `marc_xml` to multimonograph MODS data format. Args: marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. uuid (str): UUID string giving the package ID. url (str): URL of the publication (public or not). Returns: list: C...
[ "Convert", "marc_xml", "to", "multimonograph", "MODS", "data", "format", "." ]
python
train
28.444444
andrewramsay/sk8-drivers
pysk8/pysk8/core.py
https://github.com/andrewramsay/sk8-drivers/blob/67347a71762fb421f5ae65a595def5c7879e8b0c/pysk8/pysk8/core.py#L270-L298
def load_calibration(self, calibration_file=None): """Load calibration data for IMU(s) connected to this SK8. This method attempts to load a set of calibration data from a .ini file produced by the sk8_calibration_gui application (TODO link!). By default, it will look for a file name ...
[ "def", "load_calibration", "(", "self", ",", "calibration_file", "=", "None", ")", ":", "logger", ".", "debug", "(", "'Loading calibration for {}'", ".", "format", "(", "self", ".", "addr", ")", ")", "calibration_data", "=", "ConfigParser", "(", ")", "path", ...
Load calibration data for IMU(s) connected to this SK8. This method attempts to load a set of calibration data from a .ini file produced by the sk8_calibration_gui application (TODO link!). By default, it will look for a file name "sk8calib.ini" in the current working directory. This ...
[ "Load", "calibration", "data", "for", "IMU", "(", "s", ")", "connected", "to", "this", "SK8", "." ]
python
train
48.275862
hosford42/xcs
xcs/framework.py
https://github.com/hosford42/xcs/blob/183bdd0dd339e19ded3be202f86e1b38bdb9f1e5/xcs/framework.py#L940-L986
def add(self, rule): """Add a new classifier rule to the classifier set. Return a list containing zero or more rules that were deleted from the classifier by the algorithm in order to make room for the new rule. The rule argument should be a ClassifierRule instance. The behavior of this ...
[ "def", "add", "(", "self", ",", "rule", ")", ":", "assert", "isinstance", "(", "rule", ",", "ClassifierRule", ")", "condition", "=", "rule", ".", "condition", "action", "=", "rule", ".", "action", "# If the rule already exists in the population, then we virtually", ...
Add a new classifier rule to the classifier set. Return a list containing zero or more rules that were deleted from the classifier by the algorithm in order to make room for the new rule. The rule argument should be a ClassifierRule instance. The behavior of this method depends on whethe...
[ "Add", "a", "new", "classifier", "rule", "to", "the", "classifier", "set", ".", "Return", "a", "list", "containing", "zero", "or", "more", "rules", "that", "were", "deleted", "from", "the", "classifier", "by", "the", "algorithm", "in", "order", "to", "make...
python
train
43.851064
zhexiao/ezhost
ezhost/ServerCommon.py
https://github.com/zhexiao/ezhost/blob/4146bc0be14bb1bfe98ec19283d19fab420871b3/ezhost/ServerCommon.py#L365-L374
def reset_server_env(self, server_name, configure): """ reset server env to server-name :param server_name: :param configure: :return: """ env.host_string = configure[server_name]['host'] env.user = configure[server_name]['user'] env.password = con...
[ "def", "reset_server_env", "(", "self", ",", "server_name", ",", "configure", ")", ":", "env", ".", "host_string", "=", "configure", "[", "server_name", "]", "[", "'host'", "]", "env", ".", "user", "=", "configure", "[", "server_name", "]", "[", "'user'", ...
reset server env to server-name :param server_name: :param configure: :return:
[ "reset", "server", "env", "to", "server", "-", "name", ":", "param", "server_name", ":", ":", "param", "configure", ":", ":", "return", ":" ]
python
train
34
iotile/coretools
iotileemulate/iotile/emulate/internal/rpc_queue.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/internal/rpc_queue.py#L152-L163
async def stop(self): """Stop the rpc queue from inside the event loop.""" if self._rpc_task is not None: self._rpc_task.cancel() try: await self._rpc_task except asyncio.CancelledError: pass self._rpc_task = None
[ "async", "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_rpc_task", "is", "not", "None", ":", "self", ".", "_rpc_task", ".", "cancel", "(", ")", "try", ":", "await", "self", ".", "_rpc_task", "except", "asyncio", ".", "CancelledError", ":", ...
Stop the rpc queue from inside the event loop.
[ "Stop", "the", "rpc", "queue", "from", "inside", "the", "event", "loop", "." ]
python
train
23.416667
gbiggs/rtsprofile
rtsprofile/message_sending.py
https://github.com/gbiggs/rtsprofile/blob/fded6eddcb0b25fe9808b1b12336a4413ea00905/rtsprofile/message_sending.py#L282-L296
def parse_xml_node(self, node): '''Parse an xml.dom Node object representing a condition into this object. ''' self.sequence = int(node.getAttributeNS(RTS_NS, 'sequence')) c = node.getElementsByTagNameNS(RTS_NS, 'TargetComponent') if c.length != 1: raise Inva...
[ "def", "parse_xml_node", "(", "self", ",", "node", ")", ":", "self", ".", "sequence", "=", "int", "(", "node", ".", "getAttributeNS", "(", "RTS_NS", ",", "'sequence'", ")", ")", "c", "=", "node", ".", "getElementsByTagNameNS", "(", "RTS_NS", ",", "'Targe...
Parse an xml.dom Node object representing a condition into this object.
[ "Parse", "an", "xml", ".", "dom", "Node", "object", "representing", "a", "condition", "into", "this", "object", "." ]
python
train
44.333333
improbable-research/keanu
keanu-python/keanu/vertex/generated.py
https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/keanu-python/keanu/vertex/generated.py#L357-L364
def Power(base: vertex_constructor_param_types, exponent: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Raises a vertex to the power of another :param base: the base vertex :param exponent: the exponent vertex """ return Double(context.jvm_view().PowerVertex, lab...
[ "def", "Power", "(", "base", ":", "vertex_constructor_param_types", ",", "exponent", ":", "vertex_constructor_param_types", ",", "label", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "Vertex", ":", "return", "Double", "(", "context", ".", "jvm_vie...
Raises a vertex to the power of another :param base: the base vertex :param exponent: the exponent vertex
[ "Raises", "a", "vertex", "to", "the", "power", "of", "another", ":", "param", "base", ":", "the", "base", "vertex", ":", "param", "exponent", ":", "the", "exponent", "vertex" ]
python
train
47.25
fabioz/PyDev.Debugger
_pydev_bundle/pydev_versioncheck.py
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_bundle/pydev_versioncheck.py#L3-L15
def versionok_for_gui(): ''' Return True if running Python is suitable for GUI Event Integration and deeper IPython integration ''' # We require Python 2.6+ ... if sys.hexversion < 0x02060000: return False # Or Python 3.2+ if sys.hexversion >= 0x03000000 and sys.hexversion < 0x03020000: ...
[ "def", "versionok_for_gui", "(", ")", ":", "# We require Python 2.6+ ...", "if", "sys", ".", "hexversion", "<", "0x02060000", ":", "return", "False", "# Or Python 3.2+", "if", "sys", ".", "hexversion", ">=", "0x03000000", "and", "sys", ".", "hexversion", "<", "0...
Return True if running Python is suitable for GUI Event Integration and deeper IPython integration
[ "Return", "True", "if", "running", "Python", "is", "suitable", "for", "GUI", "Event", "Integration", "and", "deeper", "IPython", "integration" ]
python
train
37.230769
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Fortran.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Scanner/Fortran.py#L126-L310
def FortranScan(path_variable="FORTRANPATH"): """Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements""" # The USE statement regex matches the following: # # USE module_name # USE :: module_name # USE, INTRINSIC :: module_name # USE, NON_INTRINSIC :: modu...
[ "def", "FortranScan", "(", "path_variable", "=", "\"FORTRANPATH\"", ")", ":", "# The USE statement regex matches the following:", "#", "# USE module_name", "# USE :: module_name", "# USE, INTRINSIC :: module_name", "# USE, NON_INTRINSIC :: module_name", "#", "# Limitations"...
Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements
[ "Return", "a", "prototype", "Scanner", "instance", "for", "scanning", "source", "files", "for", "Fortran", "USE", "&", "INCLUDE", "statements" ]
python
train
48.897297
saltstack/salt
salt/modules/rh_ip.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/rh_ip.py#L320-L356
def _parse_settings_bond_1(opts, iface, bond_def): ''' Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting. ''' bond = {'mode': '1'} for binding in ['miim...
[ "def", "_parse_settings_bond_1", "(", "opts", ",", "iface", ",", "bond_def", ")", ":", "bond", "=", "{", "'mode'", ":", "'1'", "}", "for", "binding", "in", "[", "'miimon'", ",", "'downdelay'", ",", "'updelay'", "]", ":", "if", "binding", "in", "opts", ...
Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this function will log what the Interface, Setting and what it was expecting.
[ "Filters", "given", "options", "and", "outputs", "valid", "settings", "for", "bond1", ".", "If", "an", "option", "has", "a", "value", "that", "is", "not", "expected", "this", "function", "will", "log", "what", "the", "Interface", "Setting", "and", "what", ...
python
train
34.054054
ic-labs/django-icekit
icekit/utils/search/facets.py
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/utils/search/facets.py#L118-L120
def get_applicable_values(self): """Return selected values that will affect the search result""" return [v for v in self._values if v.is_active and not v.is_all_results]
[ "def", "get_applicable_values", "(", "self", ")", ":", "return", "[", "v", "for", "v", "in", "self", ".", "_values", "if", "v", ".", "is_active", "and", "not", "v", ".", "is_all_results", "]" ]
Return selected values that will affect the search result
[ "Return", "selected", "values", "that", "will", "affect", "the", "search", "result" ]
python
train
61
BlueBrain/NeuroM
examples/synthesis_json.py
https://github.com/BlueBrain/NeuroM/blob/254bb73535b20053d175bc4725bade662177d12b/examples/synthesis_json.py#L92-L100
def transform_header(mtype_name): '''Add header to json output to wrap around distribution data. ''' head_dict = OrderedDict() head_dict["m-type"] = mtype_name head_dict["components"] = defaultdict(OrderedDict) return head_dict
[ "def", "transform_header", "(", "mtype_name", ")", ":", "head_dict", "=", "OrderedDict", "(", ")", "head_dict", "[", "\"m-type\"", "]", "=", "mtype_name", "head_dict", "[", "\"components\"", "]", "=", "defaultdict", "(", "OrderedDict", ")", "return", "head_dict"...
Add header to json output to wrap around distribution data.
[ "Add", "header", "to", "json", "output", "to", "wrap", "around", "distribution", "data", "." ]
python
train
27.222222
project-ncl/pnc-cli
pnc_cli/swagger_client/apis/buildconfigurationsets_api.py
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/buildconfigurationsets_api.py#L511-L535
def delete_specific(self, id, **kwargs): """ Removes a specific Build Configuration Set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >...
[ "def", "delete_specific", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "delete_specific_with_http_info"...
Removes a specific Build Configuration Set This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(re...
[ "Removes", "a", "specific", "Build", "Configuration", "Set", "This", "method", "makes", "a", "synchronous", "HTTP", "request", "by", "default", ".", "To", "make", "an", "asynchronous", "HTTP", "request", "please", "define", "a", "callback", "function", "to", "...
python
train
40.52
numenta/htmresearch
htmresearch/data/sm_sequences.py
https://github.com/numenta/htmresearch/blob/70c096b09a577ea0432c3f3bfff4442d4871b7aa/htmresearch/data/sm_sequences.py#L349-L362
def decodeMotorInput(self, motorInputPattern): """ Decode motor command from bit vector. @param motorInputPattern (1D numpy.array) Encoded motor command. @return (1D numpy.array) Decoded motor command. """ key = self.motorEncoder.decode(motorInputPattern)[0].k...
[ "def", "decodeMotorInput", "(", "self", ",", "motorInputPattern", ")", ":", "key", "=", "self", ".", "motorEncoder", ".", "decode", "(", "motorInputPattern", ")", "[", "0", "]", ".", "keys", "(", ")", "[", "0", "]", "motorCommand", "=", "self", ".", "m...
Decode motor command from bit vector. @param motorInputPattern (1D numpy.array) Encoded motor command. @return (1D numpy.array) Decoded motor command.
[ "Decode", "motor", "command", "from", "bit", "vector", "." ]
python
train
29.714286
EventRegistry/event-registry-python
eventregistry/ReturnInfo.py
https://github.com/EventRegistry/event-registry-python/blob/534d20b616de02f5e1cd73665a02d189645dbeb6/eventregistry/ReturnInfo.py#L15-L20
def _setFlag(self, name, val, defVal): """set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal""" if not hasattr(self, "flags"): self.flags = {} if val != defVal: self.flags[name] = val
[ "def", "_setFlag", "(", "self", ",", "name", ",", "val", ",", "defVal", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"flags\"", ")", ":", "self", ".", "flags", "=", "{", "}", "if", "val", "!=", "defVal", ":", "self", ".", "flags", "[", ...
set the objects property propName if the dictKey key exists in dict and it is not the same as default value defVal
[ "set", "the", "objects", "property", "propName", "if", "the", "dictKey", "key", "exists", "in", "dict", "and", "it", "is", "not", "the", "same", "as", "default", "value", "defVal" ]
python
train
48.333333
Jajcus/pyxmpp2
pyxmpp2/ext/muc/muccore.py
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/muc/muccore.py#L512-L526
def clear(self): """ Clear the content of `self.xmlnode` removing all <item/>, <status/>, etc. """ if not self.xmlnode.children: return n=self.xmlnode.children while n: ns=n.ns() if ns and ns.getContent()!=MUC_USER_NS: p...
[ "def", "clear", "(", "self", ")", ":", "if", "not", "self", ".", "xmlnode", ".", "children", ":", "return", "n", "=", "self", ".", "xmlnode", ".", "children", "while", "n", ":", "ns", "=", "n", ".", "ns", "(", ")", "if", "ns", "and", "ns", ".",...
Clear the content of `self.xmlnode` removing all <item/>, <status/>, etc.
[ "Clear", "the", "content", "of", "self", ".", "xmlnode", "removing", "all", "<item", "/", ">", "<status", "/", ">", "etc", "." ]
python
valid
27.2
PyCQA/astroid
astroid/bases.py
https://github.com/PyCQA/astroid/blob/e0a298df55b15abcb77c2a93253f5ab7be52d0fb/astroid/bases.py#L359-L382
def infer_call_result(self, caller, context): """ The boundnode of the regular context with a function called on ``object.__new__`` will be of type ``object``, which is incorrect for the argument in general. If no context is given the ``object.__new__`` call argument will ...
[ "def", "infer_call_result", "(", "self", ",", "caller", ",", "context", ")", ":", "# If we're unbound method __new__ of builtin object, the result is an", "# instance of the class given as first argument.", "if", "(", "self", ".", "_proxied", ".", "name", "==", "\"__new__\"",...
The boundnode of the regular context with a function called on ``object.__new__`` will be of type ``object``, which is incorrect for the argument in general. If no context is given the ``object.__new__`` call argument will correctly inferred except when inside a call that requires ...
[ "The", "boundnode", "of", "the", "regular", "context", "with", "a", "function", "called", "on", "object", ".", "__new__", "will", "be", "of", "type", "object", "which", "is", "incorrect", "for", "the", "argument", "in", "general", ".", "If", "no", "context...
python
train
47.666667
explosion/thinc
thinc/rates.py
https://github.com/explosion/thinc/blob/90129be5f0d6c665344245a7c37dbe1b8afceea2/thinc/rates.py#L26-L40
def compounding(start, stop, compound, t=0.0): """Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. ...
[ "def", "compounding", "(", "start", ",", "stop", ",", "compound", ",", "t", "=", "0.0", ")", ":", "curr", "=", "float", "(", "start", ")", "while", "True", ":", "yield", "_clip", "(", "curr", ",", "start", ",", "stop", ")", "curr", "*=", "compound"...
Yield an infinite series of compounding values. Each time the generator is called, a value is produced by multiplying the previous value by the compound rate. EXAMPLE: >>> sizes = compounding(1., 10., 1.5) >>> assert next(sizes) == 1. >>> assert next(sizes) == 1 * 1.5 >>> assert nex...
[ "Yield", "an", "infinite", "series", "of", "compounding", "values", ".", "Each", "time", "the", "generator", "is", "called", "a", "value", "is", "produced", "by", "multiplying", "the", "previous", "value", "by", "the", "compound", "rate", "." ]
python
train
32.866667
inasafe/inasafe
safe/gui/widgets/dock.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/widgets/dock.py#L811-L864
def show_print_dialog(self): """Open the print dialog""" if not self.impact_function: # Now try to read the keywords and show them in the dock try: active_layer = self.iface.activeLayer() keywords = self.keyword_io.read_keywords(active_layer) ...
[ "def", "show_print_dialog", "(", "self", ")", ":", "if", "not", "self", ".", "impact_function", ":", "# Now try to read the keywords and show them in the dock", "try", ":", "active_layer", "=", "self", ".", "iface", ".", "activeLayer", "(", ")", "keywords", "=", "...
Open the print dialog
[ "Open", "the", "print", "dialog" ]
python
train
43.296296
coops/r53
src/r53/r53.py
https://github.com/coops/r53/blob/3c4e7242ad65b0e1ad4ba6b4ac893c7d501ceb0a/src/r53/r53.py#L26-L37
def lookup_zone(conn, zone): """Look up a zone ID for a zone string. Args: conn: boto.route53.Route53Connection zone: string eg. foursquare.com Returns: zone ID eg. ZE2DYFZDWGSL4. Raises: ZoneNotFoundError if zone not found.""" all_zones = conn.get_all_hosted_zones() for resp in all_zones['ListHost...
[ "def", "lookup_zone", "(", "conn", ",", "zone", ")", ":", "all_zones", "=", "conn", ".", "get_all_hosted_zones", "(", ")", "for", "resp", "in", "all_zones", "[", "'ListHostedZonesResponse'", "]", "[", "'HostedZones'", "]", ":", "if", "resp", "[", "'Name'", ...
Look up a zone ID for a zone string. Args: conn: boto.route53.Route53Connection zone: string eg. foursquare.com Returns: zone ID eg. ZE2DYFZDWGSL4. Raises: ZoneNotFoundError if zone not found.
[ "Look", "up", "a", "zone", "ID", "for", "a", "zone", "string", "." ]
python
test
42.75
summa-tx/riemann
riemann/simple.py
https://github.com/summa-tx/riemann/blob/04ae336dfd4007ceaed748daadc91cc32fa278ec/riemann/simple.py#L173-L192
def p2sh_input_and_witness(outpoint, stack_script, redeem_script, sequence=None): ''' OutPoint, str, str, int -> (TxIn, InputWitness) Create a signed legacy TxIn from a p2pkh prevout Create an empty InputWitness for it Useful for transactions spending some witness and some...
[ "def", "p2sh_input_and_witness", "(", "outpoint", ",", "stack_script", ",", "redeem_script", ",", "sequence", "=", "None", ")", ":", "if", "sequence", "is", "None", ":", "sequence", "=", "guess_sequence", "(", "redeem_script", ")", "stack_script", "=", "script_s...
OutPoint, str, str, int -> (TxIn, InputWitness) Create a signed legacy TxIn from a p2pkh prevout Create an empty InputWitness for it Useful for transactions spending some witness and some legacy prevouts
[ "OutPoint", "str", "str", "int", "-", ">", "(", "TxIn", "InputWitness", ")", "Create", "a", "signed", "legacy", "TxIn", "from", "a", "p2pkh", "prevout", "Create", "an", "empty", "InputWitness", "for", "it", "Useful", "for", "transactions", "spending", "some"...
python
train
37.4
bitcraze/crazyflie-lib-python
cflib/crtp/radiodriver.py
https://github.com/bitcraze/crazyflie-lib-python/blob/f6ebb4eb315bbe6e02db518936ac17fb615b2af8/cflib/crtp/radiodriver.py#L434-L451
def _send_packet_safe(self, cr, packet): """ Adds 1bit counter to CRTP header to guarantee that no ack (downlink) payload are lost and no uplink packet are duplicated. The caller should resend packet if not acked (ie. same as with a direct call to crazyradio.send_packet) ...
[ "def", "_send_packet_safe", "(", "self", ",", "cr", ",", "packet", ")", ":", "# packet = bytearray(packet)", "packet", "[", "0", "]", "&=", "0xF3", "packet", "[", "0", "]", "|=", "self", ".", "_curr_up", "<<", "3", "|", "self", ".", "_curr_down", "<<", ...
Adds 1bit counter to CRTP header to guarantee that no ack (downlink) payload are lost and no uplink packet are duplicated. The caller should resend packet if not acked (ie. same as with a direct call to crazyradio.send_packet)
[ "Adds", "1bit", "counter", "to", "CRTP", "header", "to", "guarantee", "that", "no", "ack", "(", "downlink", ")", "payload", "are", "lost", "and", "no", "uplink", "packet", "are", "duplicated", ".", "The", "caller", "should", "resend", "packet", "if", "not"...
python
train
40.611111
cisco-sas/kitty
kitty/model/high_level/base.py
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/model/high_level/base.py#L190-L202
def get_stages(self): ''' :return: dictionary of information regarding the stages in the fuzzing session .. note:: structure: { current: ['stage1', 'stage2', 'stage3'], 'stages': {'source1': ['dest1', 'dest2'], 'source2': ['dest1', 'dest3']}} ''' sequence = self.get...
[ "def", "get_stages", "(", "self", ")", ":", "sequence", "=", "self", ".", "get_sequence", "(", ")", "return", "{", "'current'", ":", "[", "e", ".", "dst", ".", "get_name", "(", ")", "for", "e", "in", "sequence", "]", ",", "'stages'", ":", "{", "e",...
:return: dictionary of information regarding the stages in the fuzzing session .. note:: structure: { current: ['stage1', 'stage2', 'stage3'], 'stages': {'source1': ['dest1', 'dest2'], 'source2': ['dest1', 'dest3']}}
[ ":", "return", ":", "dictionary", "of", "information", "regarding", "the", "stages", "in", "the", "fuzzing", "session" ]
python
train
37.384615
christophertbrown/bioscripts
ctbBio/sam2fastq.py
https://github.com/christophertbrown/bioscripts/blob/83b2566b3a5745437ec651cd6cafddd056846240/ctbBio/sam2fastq.py#L13-L24
def print_single(line, rev): """ print single reads to stderr """ if rev is True: seq = rc(['', line[9]])[1] qual = line[10][::-1] else: seq = line[9] qual = line[10] fq = ['@%s' % line[0], seq, '+%s' % line[0], qual] print('\n'.join(fq), file = sys.stderr)
[ "def", "print_single", "(", "line", ",", "rev", ")", ":", "if", "rev", "is", "True", ":", "seq", "=", "rc", "(", "[", "''", ",", "line", "[", "9", "]", "]", ")", "[", "1", "]", "qual", "=", "line", "[", "10", "]", "[", ":", ":", "-", "1",...
print single reads to stderr
[ "print", "single", "reads", "to", "stderr" ]
python
train
25.5
bsolomon1124/pyfinance
pyfinance/returns.py
https://github.com/bsolomon1124/pyfinance/blob/c95925209a809b4e648e79cbeaf7711d8e5ff1a6/pyfinance/returns.py#L585-L599
def gain_to_loss_ratio(self): """Gain-to-loss ratio, ratio of positive to negative returns. Formula: (n pos. / n neg.) * (avg. up-month return / avg. down-month return) [Source: CFA Institute] Returns ------- float """ gt = self > 0 lt =...
[ "def", "gain_to_loss_ratio", "(", "self", ")", ":", "gt", "=", "self", ">", "0", "lt", "=", "self", "<", "0", "return", "(", "nansum", "(", "gt", ")", "/", "nansum", "(", "lt", ")", ")", "*", "(", "self", "[", "gt", "]", ".", "mean", "(", ")"...
Gain-to-loss ratio, ratio of positive to negative returns. Formula: (n pos. / n neg.) * (avg. up-month return / avg. down-month return) [Source: CFA Institute] Returns ------- float
[ "Gain", "-", "to", "-", "loss", "ratio", "ratio", "of", "positive", "to", "negative", "returns", "." ]
python
train
26.266667
eqcorrscan/EQcorrscan
eqcorrscan/utils/mag_calc.py
https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/mag_calc.py#L474-L810
def amp_pick_event(event, st, respdir, chans=['Z'], var_wintype=True, winlen=0.9, pre_pick=0.2, pre_filt=True, lowcut=1.0, highcut=20.0, corners=4, min_snr=1.0, plot=False, remove_old=False, ps_multiplier=0.34, velocity=False): """ Pick amplitudes for loc...
[ "def", "amp_pick_event", "(", "event", ",", "st", ",", "respdir", ",", "chans", "=", "[", "'Z'", "]", ",", "var_wintype", "=", "True", ",", "winlen", "=", "0.9", ",", "pre_pick", "=", "0.2", ",", "pre_filt", "=", "True", ",", "lowcut", "=", "1.0", ...
Pick amplitudes for local magnitude for a single event. Looks for maximum peak-to-trough amplitude for a channel in a stream, and picks this amplitude and period. There are a few things it does internally to stabilise the result: 1. Applies a given filter to the data - very necessary for small ...
[ "Pick", "amplitudes", "for", "local", "magnitude", "for", "a", "single", "event", "." ]
python
train
46.985163
HazyResearch/pdftotree
pdftotree/utils/display_utils.py
https://github.com/HazyResearch/pdftotree/blob/5890d668b475d5d3058d1d886aafbfd83268c440/pdftotree/utils/display_utils.py#L65-L74
def pdf_to_img(pdf_file, page_num, page_width, page_height): """ Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object """ img = Image(filename="{}[{}]".format(pdf_file, page_num - 1)) i...
[ "def", "pdf_to_img", "(", "pdf_file", ",", "page_num", ",", "page_width", ",", "page_height", ")", ":", "img", "=", "Image", "(", "filename", "=", "\"{}[{}]\"", ".", "format", "(", "pdf_file", ",", "page_num", "-", "1", ")", ")", "img", ".", "resize", ...
Converts pdf file into image :param pdf_file: path to the pdf file :param page_num: page number to convert (index starting at 1) :return: wand image object
[ "Converts", "pdf", "file", "into", "image", ":", "param", "pdf_file", ":", "path", "to", "the", "pdf", "file", ":", "param", "page_num", ":", "page", "number", "to", "convert", "(", "index", "starting", "at", "1", ")", ":", "return", ":", "wand", "imag...
python
train
36
frostming/marko
marko/inline.py
https://github.com/frostming/marko/blob/1cd030b665fa37bad1f8b3a25a89ce1a7c491dde/marko/inline.py#L39-L43
def find(cls, text): """This method should return an iterable containing matches of this element.""" if isinstance(cls.pattern, string_types): cls.pattern = re.compile(cls.pattern) return cls.pattern.finditer(text)
[ "def", "find", "(", "cls", ",", "text", ")", ":", "if", "isinstance", "(", "cls", ".", "pattern", ",", "string_types", ")", ":", "cls", ".", "pattern", "=", "re", ".", "compile", "(", "cls", ".", "pattern", ")", "return", "cls", ".", "pattern", "."...
This method should return an iterable containing matches of this element.
[ "This", "method", "should", "return", "an", "iterable", "containing", "matches", "of", "this", "element", "." ]
python
train
49.2
ethpm/py-ethpm
ethpm/utils/uri.py
https://github.com/ethpm/py-ethpm/blob/81ed58d7c636fe00c6770edeb0401812b1a5e8fc/ethpm/utils/uri.py#L55-L79
def is_valid_github_uri(uri: URI, expected_path_terms: Tuple[str, ...]) -> bool: """ Return a bool indicating whether or not the URI fulfills the following specs Valid Github URIs *must*: - Have 'https' scheme - Have 'api.github.com' authority - Have a path that contains all "expected_path_terms...
[ "def", "is_valid_github_uri", "(", "uri", ":", "URI", ",", "expected_path_terms", ":", "Tuple", "[", "str", ",", "...", "]", ")", "->", "bool", ":", "if", "not", "is_text", "(", "uri", ")", ":", "return", "False", "parsed", "=", "parse", ".", "urlparse...
Return a bool indicating whether or not the URI fulfills the following specs Valid Github URIs *must*: - Have 'https' scheme - Have 'api.github.com' authority - Have a path that contains all "expected_path_terms"
[ "Return", "a", "bool", "indicating", "whether", "or", "not", "the", "URI", "fulfills", "the", "following", "specs", "Valid", "Github", "URIs", "*", "must", "*", ":", "-", "Have", "https", "scheme", "-", "Have", "api", ".", "github", ".", "com", "authorit...
python
train
29.64
Azure/azure-cosmos-table-python
azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py
https://github.com/Azure/azure-cosmos-table-python/blob/a7b618f6bddc465c9fdf899ea2971dfe4d04fcf0/azure-cosmosdb-table/azure/cosmosdb/table/tableservice.py#L202-L248
def generate_account_shared_access_signature(self, resource_types, permission, expiry, start=None, ip=None, protocol=None): ''' Generates a shared access signature for the table service. Use the returned signature with the sas_token parameter of T...
[ "def", "generate_account_shared_access_signature", "(", "self", ",", "resource_types", ",", "permission", ",", "expiry", ",", "start", "=", "None", ",", "ip", "=", "None", ",", "protocol", "=", "None", ")", ":", "_validate_not_none", "(", "'self.account_name'", ...
Generates a shared access signature for the table service. Use the returned signature with the sas_token parameter of TableService. :param ResourceTypes resource_types: Specifies the resource types that are accessible with the account SAS. :param AccountPermissions permission: ...
[ "Generates", "a", "shared", "access", "signature", "for", "the", "table", "service", ".", "Use", "the", "returned", "signature", "with", "the", "sas_token", "parameter", "of", "TableService", "." ]
python
train
60.893617
funilrys/PyFunceble
PyFunceble/mining.py
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/mining.py#L243-L252
def _backup(self): """ Backup the mined informations. """ if PyFunceble.CONFIGURATION["mining"]: # The mining is activated. # We backup our mined informations. Dict(PyFunceble.INTERN["mined"]).to_json(self.file)
[ "def", "_backup", "(", "self", ")", ":", "if", "PyFunceble", ".", "CONFIGURATION", "[", "\"mining\"", "]", ":", "# The mining is activated.", "# We backup our mined informations.", "Dict", "(", "PyFunceble", ".", "INTERN", "[", "\"mined\"", "]", ")", ".", "to_json...
Backup the mined informations.
[ "Backup", "the", "mined", "informations", "." ]
python
test
27.2
magrathealabs/feito
feito/messages.py
https://github.com/magrathealabs/feito/blob/4179e40233ccf6e5a6c9892e528595690ce9ef43/feito/messages.py#L10-L24
def commit_format(self): """ Formats the analysis into a simpler dictionary with the line, file and message values to be commented on a commit. Returns a list of dictionaries """ formatted_analyses = [] for analyze in self.analysis['messages']: for...
[ "def", "commit_format", "(", "self", ")", ":", "formatted_analyses", "=", "[", "]", "for", "analyze", "in", "self", ".", "analysis", "[", "'messages'", "]", ":", "formatted_analyses", ".", "append", "(", "{", "'message'", ":", "f\"{analyze['source']}: {analyze['...
Formats the analysis into a simpler dictionary with the line, file and message values to be commented on a commit. Returns a list of dictionaries
[ "Formats", "the", "analysis", "into", "a", "simpler", "dictionary", "with", "the", "line", "file", "and", "message", "values", "to", "be", "commented", "on", "a", "commit", ".", "Returns", "a", "list", "of", "dictionaries" ]
python
train
38.933333
linnarsson-lab/loompy
loompy/loom_view.py
https://github.com/linnarsson-lab/loompy/blob/62c8373a92b058753baa3a95331fb541f560f599/loompy/loom_view.py#L45-L68
def permute(self, ordering: np.ndarray, *, axis: int) -> None: """ Permute the view, by permuting its layers, attributes and graphs Args: ordering (np.ndarray): The desired ordering along the axis axis (int): 0, permute rows; 1, permute columns """ if axis not in (0, 1): raise ValueError("Axis mu...
[ "def", "permute", "(", "self", ",", "ordering", ":", "np", ".", "ndarray", ",", "*", ",", "axis", ":", "int", ")", "->", "None", ":", "if", "axis", "not", "in", "(", "0", ",", "1", ")", ":", "raise", "ValueError", "(", "\"Axis must be 0 (rows) or 1 (...
Permute the view, by permuting its layers, attributes and graphs Args: ordering (np.ndarray): The desired ordering along the axis axis (int): 0, permute rows; 1, permute columns
[ "Permute", "the", "view", "by", "permuting", "its", "layers", "attributes", "and", "graphs" ]
python
train
31.75
zimeon/iiif
iiif/info.py
https://github.com/zimeon/iiif/blob/9d10018d01202fa2a76dfa61598dc6eca07b471f/iiif/info.py#L296-L310
def level(self): """Extract level number from compliance profile URI. Returns integer level number or raises IIIFInfoError """ m = re.match( self.compliance_prefix + r'(\d)' + self.compliance_suffix + r'$', self.compliance) ...
[ "def", "level", "(", "self", ")", ":", "m", "=", "re", ".", "match", "(", "self", ".", "compliance_prefix", "+", "r'(\\d)'", "+", "self", ".", "compliance_suffix", "+", "r'$'", ",", "self", ".", "compliance", ")", "if", "(", "m", ")", ":", "return", ...
Extract level number from compliance profile URI. Returns integer level number or raises IIIFInfoError
[ "Extract", "level", "number", "from", "compliance", "profile", "URI", "." ]
python
train
30.4
brutasse/graphite-api
graphite_api/functions.py
https://github.com/brutasse/graphite-api/blob/0886b7adcf985a1e8bcb084f6dd1dc166a3f3dff/graphite_api/functions.py#L477-L520
def keepLastValue(requestContext, seriesList, limit=INF): """ Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over. Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line. ...
[ "def", "keepLastValue", "(", "requestContext", ",", "seriesList", ",", "limit", "=", "INF", ")", ":", "for", "series", "in", "seriesList", ":", "series", ".", "name", "=", "\"keepLastValue(%s)\"", "%", "(", "series", ".", "name", ")", "series", ".", "pathE...
Takes one metric or a wildcard seriesList, and optionally a limit to the number of 'None' values to skip over. Continues the line with the last received value when gaps ('None' values) appear in your data, rather than breaking your line. Example:: &target=keepLastValue(Server01.connections.han...
[ "Takes", "one", "metric", "or", "a", "wildcard", "seriesList", "and", "optionally", "a", "limit", "to", "the", "number", "of", "None", "values", "to", "skip", "over", ".", "Continues", "the", "line", "with", "the", "last", "received", "value", "when", "gap...
python
train
37.363636
pantsbuild/pants
src/python/pants/option/arg_splitter.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/src/python/pants/option/arg_splitter.py#L214-L230
def _consume_scope(self): """Returns a pair (scope, list of flags encountered in that scope). Note that the flag may be explicitly scoped, and therefore not actually belong to this scope. For example, in: ./pants --compile-java-partition-size-hint=100 compile <target> --compile-java-partition-si...
[ "def", "_consume_scope", "(", "self", ")", ":", "if", "not", "self", ".", "_at_scope", "(", ")", ":", "return", "None", ",", "[", "]", "scope", "=", "self", ".", "_unconsumed_args", ".", "pop", "(", ")", "flags", "=", "self", ".", "_consume_flags", "...
Returns a pair (scope, list of flags encountered in that scope). Note that the flag may be explicitly scoped, and therefore not actually belong to this scope. For example, in: ./pants --compile-java-partition-size-hint=100 compile <target> --compile-java-partition-size-hint should be treated as if i...
[ "Returns", "a", "pair", "(", "scope", "list", "of", "flags", "encountered", "in", "that", "scope", ")", "." ]
python
train
32.764706
craigahobbs/chisel
src/chisel/util.py
https://github.com/craigahobbs/chisel/blob/d306a9eae2ff757647c6ca1c933bc944efa5c326/src/chisel/util.py#L149-L165
def import_submodules(package, parent_package=None, exclude_submodules=None): """ Generator which imports all submodules of a module, recursively, including subpackages :param package: package name (e.g 'chisel.util'); may be relative if parent_package is provided :type package: str :param parent_p...
[ "def", "import_submodules", "(", "package", ",", "parent_package", "=", "None", ",", "exclude_submodules", "=", "None", ")", ":", "exclude_submodules_dot", "=", "[", "x", "+", "'.'", "for", "x", "in", "exclude_submodules", "]", "if", "exclude_submodules", "else"...
Generator which imports all submodules of a module, recursively, including subpackages :param package: package name (e.g 'chisel.util'); may be relative if parent_package is provided :type package: str :param parent_package: parent package name (e.g 'chisel') :type package: str :rtype: iterator of ...
[ "Generator", "which", "imports", "all", "submodules", "of", "a", "module", "recursively", "including", "subpackages" ]
python
train
50.647059
rbuffat/pyepw
pyepw/epw.py
https://github.com/rbuffat/pyepw/blob/373d4d3c8386c8d35789f086ac5f6018c2711745/pyepw/epw.py#L7391-L7418
def _create_datadict(cls, internal_name): """Creates an object depending on `internal_name` Args: internal_name (str): IDD name Raises: ValueError: if `internal_name` cannot be matched to a data dictionary object """ if internal_name == "LOCATION": ...
[ "def", "_create_datadict", "(", "cls", ",", "internal_name", ")", ":", "if", "internal_name", "==", "\"LOCATION\"", ":", "return", "Location", "(", ")", "if", "internal_name", "==", "\"DESIGN CONDITIONS\"", ":", "return", "DesignConditions", "(", ")", "if", "int...
Creates an object depending on `internal_name` Args: internal_name (str): IDD name Raises: ValueError: if `internal_name` cannot be matched to a data dictionary object
[ "Creates", "an", "object", "depending", "on", "internal_name" ]
python
train
36.321429
mlperf/training
image_classification/tensorflow/official/resnet/resnet_model.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/image_classification/tensorflow/official/resnet/resnet_model.py#L67-L91
def fixed_padding(inputs, kernel_size, data_format): """Pads the input along the spatial dimensions independently of input size. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. kernel_size: The kernel to be used...
[ "def", "fixed_padding", "(", "inputs", ",", "kernel_size", ",", "data_format", ")", ":", "pad_total", "=", "kernel_size", "-", "1", "pad_beg", "=", "pad_total", "//", "2", "pad_end", "=", "pad_total", "-", "pad_beg", "if", "data_format", "==", "'channels_first...
Pads the input along the spatial dimensions independently of input size. Args: inputs: A tensor of size [batch, channels, height_in, width_in] or [batch, height_in, width_in, channels] depending on data_format. kernel_size: The kernel to be used in the conv2d or max_pool2d operation. S...
[ "Pads", "the", "input", "along", "the", "spatial", "dimensions", "independently", "of", "input", "size", "." ]
python
train
40.92
tanghaibao/goatools
goatools/semantic.py
https://github.com/tanghaibao/goatools/blob/407682e573a108864a79031f8ca19ee3bf377626/goatools/semantic.py#L111-L117
def get_term_freq(self, go_id): ''' Returns the frequency at which a particular GO term has been observed in the annotations. ''' num_ns = float(self.get_total_count(self.go2obj[go_id].namespace)) return float(self.get_count(go_id))/num_ns if num_ns != 0 else 0
[ "def", "get_term_freq", "(", "self", ",", "go_id", ")", ":", "num_ns", "=", "float", "(", "self", ".", "get_total_count", "(", "self", ".", "go2obj", "[", "go_id", "]", ".", "namespace", ")", ")", "return", "float", "(", "self", ".", "get_count", "(", ...
Returns the frequency at which a particular GO term has been observed in the annotations.
[ "Returns", "the", "frequency", "at", "which", "a", "particular", "GO", "term", "has", "been", "observed", "in", "the", "annotations", "." ]
python
train
44.428571
DataDog/integrations-core
tokumx/datadog_checks/tokumx/vendor/bson/__init__.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/tokumx/datadog_checks/tokumx/vendor/bson/__init__.py#L746-L763
def _dict_to_bson(doc, check_keys, opts, top_level=True): """Encode a document to BSON.""" if _raw_document_class(doc): return doc.raw try: elements = [] if top_level and "_id" in doc: elements.append(_name_value_to_bson(b"_id\x00", doc["_id"], ...
[ "def", "_dict_to_bson", "(", "doc", ",", "check_keys", ",", "opts", ",", "top_level", "=", "True", ")", ":", "if", "_raw_document_class", "(", "doc", ")", ":", "return", "doc", ".", "raw", "try", ":", "elements", "=", "[", "]", "if", "top_level", "and"...
Encode a document to BSON.
[ "Encode", "a", "document", "to", "BSON", "." ]
python
train
42.277778
skorch-dev/skorch
skorch/history.py
https://github.com/skorch-dev/skorch/blob/5b9b8b7b7712cb6e5aaa759d9608ea6269d5bcd3/skorch/history.py#L169-L179
def from_file(cls, f): """Load the history of a ``NeuralNet`` from a json file. Parameters ---------- f : file-like object or str """ with open_file_like(f, 'r') as fp: return cls(json.load(fp))
[ "def", "from_file", "(", "cls", ",", "f", ")", ":", "with", "open_file_like", "(", "f", ",", "'r'", ")", "as", "fp", ":", "return", "cls", "(", "json", ".", "load", "(", "fp", ")", ")" ]
Load the history of a ``NeuralNet`` from a json file. Parameters ---------- f : file-like object or str
[ "Load", "the", "history", "of", "a", "NeuralNet", "from", "a", "json", "file", "." ]
python
train
22.454545
openego/ding0
ding0/core/__init__.py
https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/core/__init__.py#L1640-L1667
def connect_generators(self, debug=False): """ Connects generators (graph nodes) to grid (graph) for every MV and LV Grid District Args ---- debug: bool, defaults to False If True, information is printed during process. """ for mv_grid_district in self.mv_gr...
[ "def", "connect_generators", "(", "self", ",", "debug", "=", "False", ")", ":", "for", "mv_grid_district", "in", "self", ".", "mv_grid_districts", "(", ")", ":", "mv_grid_district", ".", "mv_grid", ".", "connect_generators", "(", "debug", "=", "debug", ")", ...
Connects generators (graph nodes) to grid (graph) for every MV and LV Grid District Args ---- debug: bool, defaults to False If True, information is printed during process.
[ "Connects", "generators", "(", "graph", "nodes", ")", "to", "grid", "(", "graph", ")", "for", "every", "MV", "and", "LV", "Grid", "District" ]
python
train
40.928571
mitsei/dlkit
dlkit/records/adaptive/magic_parts/assessment_part_records.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/records/adaptive/magic_parts/assessment_part_records.py#L125-L150
def get_parts(self, parts=None, reference_level=0): """Recursively returns a depth-first list of all known magic parts""" if parts is None: parts = list() new_reference_level = reference_level else: self._level_in_section = self._level + reference_level ...
[ "def", "get_parts", "(", "self", ",", "parts", "=", "None", ",", "reference_level", "=", "0", ")", ":", "if", "parts", "is", "None", ":", "parts", "=", "list", "(", ")", "new_reference_level", "=", "reference_level", "else", ":", "self", ".", "_level_in_...
Recursively returns a depth-first list of all known magic parts
[ "Recursively", "returns", "a", "depth", "-", "first", "list", "of", "all", "known", "magic", "parts" ]
python
train
44.961538
fermiPy/fermipy
fermipy/diffuse/model_component.py
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/diffuse/model_component.py#L161-L172
def add_component_info(self, compinfo): """Add sub-component specific information to a particular data selection Parameters ---------- compinfo : `ModelComponentInfo` object Sub-component being added """ if self.components is None: self.component...
[ "def", "add_component_info", "(", "self", ",", "compinfo", ")", ":", "if", "self", ".", "components", "is", "None", ":", "self", ".", "components", "=", "{", "}", "self", ".", "components", "[", "compinfo", ".", "comp_key", "]", "=", "compinfo" ]
Add sub-component specific information to a particular data selection Parameters ---------- compinfo : `ModelComponentInfo` object Sub-component being added
[ "Add", "sub", "-", "component", "specific", "information", "to", "a", "particular", "data", "selection" ]
python
train
30.75
WebarchivCZ/WA-KAT
src/wa_kat/templates/static/js/Lib/site-packages/components/input_controller.py
https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/templates/static/js/Lib/site-packages/components/input_controller.py#L158-L178
def get_el(el): """ Get value of given `el` tag element. Automatically choose proper method to set the `value` based on the type of the `el`. Args: el (obj): Element reference to the input you want to convert to typeahead. Returns: ...
[ "def", "get_el", "(", "el", ")", ":", "tag_name", "=", "el", ".", "elt", ".", "tagName", ".", "lower", "(", ")", "if", "tag_name", "in", "{", "\"input\"", ",", "\"textarea\"", ",", "\"select\"", "}", ":", "return", "el", ".", "value", "else", ":", ...
Get value of given `el` tag element. Automatically choose proper method to set the `value` based on the type of the `el`. Args: el (obj): Element reference to the input you want to convert to typeahead. Returns: str: Value of the object.
[ "Get", "value", "of", "given", "el", "tag", "element", "." ]
python
train
28.47619
TheHive-Project/Cortex-Analyzers
analyzers/MISP/mispclient.py
https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MISP/mispclient.py#L238-L244
def search_url(self, searchterm): """Search for URLs :type searchterm: str :rtype: list """ return self.__search(type_attribute=self.__mispurltypes(), value=searchterm)
[ "def", "search_url", "(", "self", ",", "searchterm", ")", ":", "return", "self", ".", "__search", "(", "type_attribute", "=", "self", ".", "__mispurltypes", "(", ")", ",", "value", "=", "searchterm", ")" ]
Search for URLs :type searchterm: str :rtype: list
[ "Search", "for", "URLs", ":", "type", "searchterm", ":", "str", ":", "rtype", ":", "list" ]
python
train
30.142857
saltstack/salt
salt/modules/acme.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/acme.py#L92-L104
def _renew_by(name, window=None): ''' Date before a certificate should be renewed :param name: Common Name of the certificate (DNS name of certificate) :param window: days before expiry date to renew :return datetime object of first renewal date ''' expiry = _expires(name) if window is ...
[ "def", "_renew_by", "(", "name", ",", "window", "=", "None", ")", ":", "expiry", "=", "_expires", "(", "name", ")", "if", "window", "is", "not", "None", ":", "expiry", "=", "expiry", "-", "datetime", ".", "timedelta", "(", "days", "=", "window", ")",...
Date before a certificate should be renewed :param name: Common Name of the certificate (DNS name of certificate) :param window: days before expiry date to renew :return datetime object of first renewal date
[ "Date", "before", "a", "certificate", "should", "be", "renewed" ]
python
train
30.307692
saltstack/salt
salt/states/rdp.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/rdp.py#L15-L38
def enabled(name): ''' Enable the RDP service and make sure access to the RDP port is allowed in the firewall configuration ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} stat = __salt__['rdp.status']() if not stat: if __opts...
[ "def", "enabled", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "stat", "=", "__salt__", "[", "'rdp.status'", "]", "(", ")", "if", "...
Enable the RDP service and make sure access to the RDP port is allowed in the firewall configuration
[ "Enable", "the", "RDP", "service", "and", "make", "sure", "access", "to", "the", "RDP", "port", "is", "allowed", "in", "the", "firewall", "configuration" ]
python
train
24.541667
KnowledgeLinks/rdfframework
rdfframework/utilities/baseutilities.py
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/baseutilities.py#L170-L202
def nz(value, none_value, strict=True): ''' This function is named after an old VBA function. It returns a default value if the passed in value is None. If strict is False it will treat an empty string as None as well. example: x = None nz(x,"hello") --> "hello" ...
[ "def", "nz", "(", "value", ",", "none_value", ",", "strict", "=", "True", ")", ":", "if", "not", "DEBUG", ":", "debug", "=", "False", "else", ":", "debug", "=", "False", "if", "debug", ":", "print", "(", "\"START nz frameworkutilities.py --------------------...
This function is named after an old VBA function. It returns a default value if the passed in value is None. If strict is False it will treat an empty string as None as well. example: x = None nz(x,"hello") --> "hello" nz(x,"") --> "" y = "" ...
[ "This", "function", "is", "named", "after", "an", "old", "VBA", "function", ".", "It", "returns", "a", "default", "value", "if", "the", "passed", "in", "value", "is", "None", ".", "If", "strict", "is", "False", "it", "will", "treat", "an", "empty", "st...
python
train
31.121212
bachya/py17track
py17track/profile.py
https://github.com/bachya/py17track/blob/e6e64f2a79571433df7ee702cb4ebc4127b7ad6d/py17track/profile.py#L22-L45
async def login(self, email: str, password: str) -> bool: """Login to the profile.""" login_resp = await self._request( 'post', API_URL_USER, json={ 'version': '1.0', 'method': 'Signin', 'param': { 'E...
[ "async", "def", "login", "(", "self", ",", "email", ":", "str", ",", "password", ":", "str", ")", "->", "bool", ":", "login_resp", "=", "await", "self", ".", "_request", "(", "'post'", ",", "API_URL_USER", ",", "json", "=", "{", "'version'", ":", "'1...
Login to the profile.
[ "Login", "to", "the", "profile", "." ]
python
train
27.208333
mdickinson/bigfloat
bigfloat/context.py
https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/context.py#L296-L327
def _apply_function_in_context(cls, f, args, context): """ Apply an MPFR function 'f' to the given arguments 'args', rounding to the given context. Returns a new Mpfr object with precision taken from the current context. """ rounding = context.rounding bf = mpfr.Mpfr_t.__new__(cls) mpfr.mp...
[ "def", "_apply_function_in_context", "(", "cls", ",", "f", ",", "args", ",", "context", ")", ":", "rounding", "=", "context", ".", "rounding", "bf", "=", "mpfr", ".", "Mpfr_t", ".", "__new__", "(", "cls", ")", "mpfr", ".", "mpfr_init2", "(", "bf", ",",...
Apply an MPFR function 'f' to the given arguments 'args', rounding to the given context. Returns a new Mpfr object with precision taken from the current context.
[ "Apply", "an", "MPFR", "function", "f", "to", "the", "given", "arguments", "args", "rounding", "to", "the", "given", "context", ".", "Returns", "a", "new", "Mpfr", "object", "with", "precision", "taken", "from", "the", "current", "context", "." ]
python
train
43.75
zhanglab/psamm
psamm/datasource/sbml.py
https://github.com/zhanglab/psamm/blob/dc427848c4f9d109ca590f0afa024c63b685b3f4/psamm/datasource/sbml.py#L1309-L1334
def create_convert_sbml_id_function( compartment_prefix='C_', reaction_prefix='R_', compound_prefix='M_', decode_id=entry_id_from_cobra_encoding): """Create function for converting SBML IDs. The returned function will strip prefixes, decode the ID using the provided function. These prefixes...
[ "def", "create_convert_sbml_id_function", "(", "compartment_prefix", "=", "'C_'", ",", "reaction_prefix", "=", "'R_'", ",", "compound_prefix", "=", "'M_'", ",", "decode_id", "=", "entry_id_from_cobra_encoding", ")", ":", "def", "convert_sbml_id", "(", "entry", ")", ...
Create function for converting SBML IDs. The returned function will strip prefixes, decode the ID using the provided function. These prefixes are common on IDs in SBML models because the IDs live in a global namespace.
[ "Create", "function", "for", "converting", "SBML", "IDs", "." ]
python
train
36.076923
Neurita/boyle
boyle/nifti/utils.py
https://github.com/Neurita/boyle/blob/2dae7199849395a209c887d5f30506e1de8a9ad9/boyle/nifti/utils.py#L95-L127
def thr_img(img, thr=2., mode='+'): """ Use the given magic function name `func` to threshold with value `thr` the data of `img` and return a new nibabel.Nifti1Image. Parameters ---------- img: img-like thr: float or int The threshold value. mode: str Choices: '+' for posit...
[ "def", "thr_img", "(", "img", ",", "thr", "=", "2.", ",", "mode", "=", "'+'", ")", ":", "vol", "=", "read_img", "(", "img", ")", ".", "get_data", "(", ")", "if", "mode", "==", "'+'", ":", "mask", "=", "vol", ">", "thr", "elif", "mode", "==", ...
Use the given magic function name `func` to threshold with value `thr` the data of `img` and return a new nibabel.Nifti1Image. Parameters ---------- img: img-like thr: float or int The threshold value. mode: str Choices: '+' for positive threshold, '+-' for pos...
[ "Use", "the", "given", "magic", "function", "name", "func", "to", "threshold", "with", "value", "thr", "the", "data", "of", "img", "and", "return", "a", "new", "nibabel", ".", "Nifti1Image", ".", "Parameters", "----------", "img", ":", "img", "-", "like" ]
python
valid
26.242424
MacHu-GWU/angora-project
angora/bot/macro.py
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/bot/macro.py#L165-L171
def Alt_Fn(self, n, dl = 0): """Alt + Fn1~12 组合键 """ self.Delay(dl) self.keyboard.press_key(self.keyboard.alt_key) self.keyboard.tap_key(self.keyboard.function_keys[n]) self.keyboard.release_key(self.keyboard.alt_key)
[ "def", "Alt_Fn", "(", "self", ",", "n", ",", "dl", "=", "0", ")", ":", "self", ".", "Delay", "(", "dl", ")", "self", ".", "keyboard", ".", "press_key", "(", "self", ".", "keyboard", ".", "alt_key", ")", "self", ".", "keyboard", ".", "tap_key", "(...
Alt + Fn1~12 组合键
[ "Alt", "+", "Fn1~12", "组合键" ]
python
train
37
santoshphilip/eppy
eppy/iddgaps.py
https://github.com/santoshphilip/eppy/blob/55410ff7c11722f35bc4331ff5e00a0b86f787e1/eppy/iddgaps.py#L152-L170
def missingkeys_nonstandard(block, commdct, dtls, objectlist, afield='afiled %s'): """This is an object list where thre is no first field name to give a hint of what the first field name should be""" afield = 'afield %s' for key_txt in objectlist: key_i = dtls.index(key_txt.upper()) comm...
[ "def", "missingkeys_nonstandard", "(", "block", ",", "commdct", ",", "dtls", ",", "objectlist", ",", "afield", "=", "'afiled %s'", ")", ":", "afield", "=", "'afield %s'", "for", "key_txt", "in", "objectlist", ":", "key_i", "=", "dtls", ".", "index", "(", "...
This is an object list where thre is no first field name to give a hint of what the first field name should be
[ "This", "is", "an", "object", "list", "where", "thre", "is", "no", "first", "field", "name", "to", "give", "a", "hint", "of", "what", "the", "first", "field", "name", "should", "be" ]
python
train
38.210526
zetaops/zengine
zengine/messaging/views.py
https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/messaging/views.py#L305-L342
def unread_count(current): """ Number of unread messages for current user .. code-block:: python # request: { 'view':'_zops_unread_count', } # response: { 'status': 'OK', 'co...
[ "def", "unread_count", "(", "current", ")", ":", "unread_ntf", "=", "0", "unread_msg", "=", "0", "for", "sbs", "in", "current", ".", "user", ".", "subscriptions", ".", "objects", ".", "filter", "(", "is_visible", "=", "True", ")", ":", "try", ":", "if"...
Number of unread messages for current user .. code-block:: python # request: { 'view':'_zops_unread_count', } # response: { 'status': 'OK', 'code': 200, 'notifications': ...
[ "Number", "of", "unread", "messages", "for", "current", "user" ]
python
train
26.289474
jamesturk/scrapelib
scrapelib/__init__.py
https://github.com/jamesturk/scrapelib/blob/dcae9fa86f1fdcc4b4e90dbca12c8063bcb36525/scrapelib/__init__.py#L295-L333
def urlretrieve(self, url, filename=None, method='GET', body=None, dir=None, **kwargs): """ Save result of a request to a file, similarly to :func:`urllib.urlretrieve`. If an error is encountered may raise any of the scrapelib `exceptions`_. A filename may be provided o...
[ "def", "urlretrieve", "(", "self", ",", "url", ",", "filename", "=", "None", ",", "method", "=", "'GET'", ",", "body", "=", "None", ",", "dir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "request", "(", "method", ...
Save result of a request to a file, similarly to :func:`urllib.urlretrieve`. If an error is encountered may raise any of the scrapelib `exceptions`_. A filename may be provided or :meth:`urlretrieve` will safely create a temporary file. If a directory is provided, a file will b...
[ "Save", "result", "of", "a", "request", "to", "a", "file", "similarly", "to", ":", "func", ":", "urllib", ".", "urlretrieve", "." ]
python
train
42.102564
macbre/sql-metadata
sql_metadata.py
https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L269-L306
def generalize_sql(sql): """ Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str """ if sql is None: return None # multiple spaces sql = re.sub(r'\s{2,}', ' ', s...
[ "def", "generalize_sql", "(", "sql", ")", ":", "if", "sql", "is", "None", ":", "return", "None", "# multiple spaces", "sql", "=", "re", ".", "sub", "(", "r'\\s{2,}'", ",", "' '", ",", "sql", ")", "# MW comments", "# e.g. /* CategoryDataService::getMostVisited N....
Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str
[ "Removes", "most", "variables", "from", "an", "SQL", "query", "and", "replaces", "them", "with", "X", "or", "N", "for", "numbers", "." ]
python
train
25.789474
openpermissions/koi
koi/utils.py
https://github.com/openpermissions/koi/blob/d721f8e1dfa8f07ad265d9dec32e8aaf80a9f281/koi/utils.py#L36-L49
def listify(*args): """ Convert args to a list, unless there's one arg and it's a function, then acts a decorator. """ if (len(args) == 1) and callable(args[0]): func = args[0] @wraps(func) def _inner(*args, **kwargs): return list(func(*args, **kwargs)) r...
[ "def", "listify", "(", "*", "args", ")", ":", "if", "(", "len", "(", "args", ")", "==", "1", ")", "and", "callable", "(", "args", "[", "0", "]", ")", ":", "func", "=", "args", "[", "0", "]", "@", "wraps", "(", "func", ")", "def", "_inner", ...
Convert args to a list, unless there's one arg and it's a function, then acts a decorator.
[ "Convert", "args", "to", "a", "list", "unless", "there", "s", "one", "arg", "and", "it", "s", "a", "function", "then", "acts", "a", "decorator", "." ]
python
train
25.357143
philipsoutham/py-mysql2pgsql
mysql2pgsql/lib/postgres_db_writer.py
https://github.com/philipsoutham/py-mysql2pgsql/blob/66dc2a3a3119263b3fe77300fb636346509787ef/mysql2pgsql/lib/postgres_db_writer.py#L196-L206
def write_contents(self, table, reader): """Write the contents of `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql...
[ "def", "write_contents", "(", "self", ",", "table", ",", "reader", ")", ":", "f", "=", "self", ".", "FileObjFaker", "(", "table", ",", "reader", ".", "read", "(", "table", ")", ",", "self", ".", "process_row", ",", "self", ".", "verbose", ")", "self"...
Write the contents of `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. - `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader` object that allows reading from...
[ "Write", "the", "contents", "of", "table" ]
python
test
54
etcher-be/emiz
emiz/mission_time.py
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/mission_time.py#L51-L77
def from_string(input_str) -> 'MissionTime': # noinspection SpellCheckingInspection """ Creates a MissionTime instance from a string Format: YYYYMMDDHHMMSS Args: input_str: string to parse Returns: MissionTime instance """ match = RE_INPUT_...
[ "def", "from_string", "(", "input_str", ")", "->", "'MissionTime'", ":", "# noinspection SpellCheckingInspection", "match", "=", "RE_INPUT_STRING", ".", "match", "(", "input_str", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "f'badly formatted date/time...
Creates a MissionTime instance from a string Format: YYYYMMDDHHMMSS Args: input_str: string to parse Returns: MissionTime instance
[ "Creates", "a", "MissionTime", "instance", "from", "a", "string" ]
python
train
27.814815
HolmesNL/confidence
confidence/io.py
https://github.com/HolmesNL/confidence/blob/e14d2d8769a01fa55676716f7a2f22714c2616d3/confidence/io.py#L273-L304
def load_name(*names, load_order=DEFAULT_LOAD_ORDER, extension='yaml', missing=Missing.silent): """ Read a `.Configuration` instance by name, trying to read from files in increasing significance. The default load order is `.system`, `.user`, `.application`, `.environment`. Multiple names are combin...
[ "def", "load_name", "(", "*", "names", ",", "load_order", "=", "DEFAULT_LOAD_ORDER", ",", "extension", "=", "'yaml'", ",", "missing", "=", "Missing", ".", "silent", ")", ":", "def", "generate_sources", "(", ")", ":", "# argument order for product matters, for name...
Read a `.Configuration` instance by name, trying to read from files in increasing significance. The default load order is `.system`, `.user`, `.application`, `.environment`. Multiple names are combined with multiple loaders using names as the 'inner loop / selector', loading ``/etc/name1.yaml`` and ``/...
[ "Read", "a", ".", "Configuration", "instance", "by", "name", "trying", "to", "read", "from", "files", "in", "increasing", "significance", ".", "The", "default", "load", "order", "is", ".", "system", ".", "user", ".", "application", ".", "environment", "." ]
python
train
50.53125
kennethreitz/legit
legit/utils.py
https://github.com/kennethreitz/legit/blob/699802c5be665bd358456a940953b5c1d8672754/legit/utils.py#L8-L20
def status_log(func, message, *args, **kwargs): """Emits header message, executes a callable, and echoes the return strings.""" click.echo(message) log = func(*args, **kwargs) if log: out = [] for line in log.split('\n'): if not line.startswith('#'): out.ap...
[ "def", "status_log", "(", "func", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "click", ".", "echo", "(", "message", ")", "log", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "log", ":", "out", "=", ...
Emits header message, executes a callable, and echoes the return strings.
[ "Emits", "header", "message", "executes", "a", "callable", "and", "echoes", "the", "return", "strings", "." ]
python
train
27.692308
instana/python-sensor
instana/fsm.py
https://github.com/instana/python-sensor/blob/58aecb90924c48bafcbc4f93bd9b7190980918bc/instana/fsm.py#L168-L193
def __get_real_pid(self): """ Attempts to determine the true process ID by querying the /proc/<pid>/sched file. This works on systems with a proc filesystem. Otherwise default to os default. """ pid = None if os.path.exists("/proc/"): sched_file = "/...
[ "def", "__get_real_pid", "(", "self", ")", ":", "pid", "=", "None", "if", "os", ".", "path", ".", "exists", "(", "\"/proc/\"", ")", ":", "sched_file", "=", "\"/proc/%d/sched\"", "%", "os", ".", "getpid", "(", ")", "if", "os", ".", "path", ".", "isfil...
Attempts to determine the true process ID by querying the /proc/<pid>/sched file. This works on systems with a proc filesystem. Otherwise default to os default.
[ "Attempts", "to", "determine", "the", "true", "process", "ID", "by", "querying", "the", "/", "proc", "/", "<pid", ">", "/", "sched", "file", ".", "This", "works", "on", "systems", "with", "a", "proc", "filesystem", ".", "Otherwise", "default", "to", "os"...
python
train
32.038462
shaiguitar/snowclient.py
snowclient/api.py
https://github.com/shaiguitar/snowclient.py/blob/6bb513576d3b37612a7a4da225140d134f3e1c82/snowclient/api.py#L80-L89
def req(self, meth, url, http_data=''): """ sugar that wraps the 'requests' module with basic auth and some headers. """ self.logger.debug("Making request: %s %s\nBody:%s" % (meth, url, http_data)) req_method = getattr(requests, meth) return (req_method(url, ...
[ "def", "req", "(", "self", ",", "meth", ",", "url", ",", "http_data", "=", "''", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Making request: %s %s\\nBody:%s\"", "%", "(", "meth", ",", "url", ",", "http_data", ")", ")", "req_method", "=", "ge...
sugar that wraps the 'requests' module with basic auth and some headers.
[ "sugar", "that", "wraps", "the", "requests", "module", "with", "basic", "auth", "and", "some", "headers", "." ]
python
train
51.1
PmagPy/PmagPy
programs/orientation_magic.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/programs/orientation_magic.py#L8-L111
def main(): """ NAME orientation_magic.py DESCRIPTION takes tab delimited field notebook information and converts to MagIC formatted tables SYNTAX orientation_magic.py [command line options] OPTIONS -f FILE: specify input file, default is: orient.txt -Fsa F...
[ "def", "main", "(", ")", ":", "args", "=", "sys", ".", "argv", "if", "\"-h\"", "in", "args", ":", "print", "(", "main", ".", "__doc__", ")", "sys", ".", "exit", "(", ")", "else", ":", "info", "=", "[", "[", "'WD'", ",", "False", ",", "'.'", "...
NAME orientation_magic.py DESCRIPTION takes tab delimited field notebook information and converts to MagIC formatted tables SYNTAX orientation_magic.py [command line options] OPTIONS -f FILE: specify input file, default is: orient.txt -Fsa FILE: specify output file...
[ "NAME", "orientation_magic", ".", "py" ]
python
train
63.548077
mastro35/tyler
tyler.py
https://github.com/mastro35/tyler/blob/9f26ca4db45308a006f7848fa58079ca28eb9873/tyler.py#L139-L158
def main(): '''Entry point''' if len(sys.argv) == 1: print("Usage: tyler [filename]") sys.exit(0) filename = sys.argv[1] if not os.path.isfile(filename): print("Specified file does not exists") sys.exit(8) my_tyler = Tyler(filename=filename) while True: ...
[ "def", "main", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "==", "1", ":", "print", "(", "\"Usage: tyler [filename]\"", ")", "sys", ".", "exit", "(", "0", ")", "filename", "=", "sys", ".", "argv", "[", "1", "]", "if", "not", "os", ...
Entry point
[ "Entry", "point" ]
python
train
24.65
django-import-export/django-import-export
import_export/resources.py
https://github.com/django-import-export/django-import-export/blob/127f00d03fd0ad282615b064b7f444a639e6ff0c/import_export/resources.py#L297-L310
def save_instance(self, instance, using_transactions=True, dry_run=False): """ Takes care of saving the object to the database. Keep in mind that this is done by calling ``instance.save()``, so objects are not created in bulk! """ self.before_save_instance(instance, usin...
[ "def", "save_instance", "(", "self", ",", "instance", ",", "using_transactions", "=", "True", ",", "dry_run", "=", "False", ")", ":", "self", ".", "before_save_instance", "(", "instance", ",", "using_transactions", ",", "dry_run", ")", "if", "not", "using_tran...
Takes care of saving the object to the database. Keep in mind that this is done by calling ``instance.save()``, so objects are not created in bulk!
[ "Takes", "care", "of", "saving", "the", "object", "to", "the", "database", "." ]
python
train
41.285714
aws/aws-encryption-sdk-python
src/aws_encryption_sdk/internal/formatting/__init__.py
https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/__init__.py#L61-L76
def _final_frame_length(header, final_frame_bytes): """Calculates the length of a final ciphertext frame, given a complete header and the number of bytes of ciphertext in the final frame. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :param ...
[ "def", "_final_frame_length", "(", "header", ",", "final_frame_bytes", ")", ":", "final_frame_length", "=", "4", "# Sequence Number End", "final_frame_length", "+=", "4", "# Sequence Number", "final_frame_length", "+=", "header", ".", "algorithm", ".", "iv_len", "# IV",...
Calculates the length of a final ciphertext frame, given a complete header and the number of bytes of ciphertext in the final frame. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :param int final_frame_bytes: Bytes of ciphertext in the final fra...
[ "Calculates", "the", "length", "of", "a", "final", "ciphertext", "frame", "given", "a", "complete", "header", "and", "the", "number", "of", "bytes", "of", "ciphertext", "in", "the", "final", "frame", "." ]
python
train
48
brosner/django-timezones
timezones/utils.py
https://github.com/brosner/django-timezones/blob/43b437c39533e1832562a2c69247b89ae1af169e/timezones/utils.py#L16-L27
def adjust_datetime_to_timezone(value, from_tz, to_tz=None): """ Given a ``datetime`` object adjust it according to the from_tz timezone string into the to_tz timezone string. """ if to_tz is None: to_tz = settings.TIME_ZONE if value.tzinfo is None: if not hasattr(from_tz, "local...
[ "def", "adjust_datetime_to_timezone", "(", "value", ",", "from_tz", ",", "to_tz", "=", "None", ")", ":", "if", "to_tz", "is", "None", ":", "to_tz", "=", "settings", ".", "TIME_ZONE", "if", "value", ".", "tzinfo", "is", "None", ":", "if", "not", "hasattr"...
Given a ``datetime`` object adjust it according to the from_tz timezone string into the to_tz timezone string.
[ "Given", "a", "datetime", "object", "adjust", "it", "according", "to", "the", "from_tz", "timezone", "string", "into", "the", "to_tz", "timezone", "string", "." ]
python
train
39.333333
yyuu/botornado
botornado/s3/bucket.py
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/botornado/s3/bucket.py#L142-L173
def get_all_keys(self, headers=None, callback=None, **params): """ A lower-level method for listing contents of a bucket. This closely models the actual S3 API and requires you to manually handle the paging of results. For a higher-level method that handles the details of paging...
[ "def", "get_all_keys", "(", "self", ",", "headers", "=", "None", ",", "callback", "=", "None", ",", "*", "*", "params", ")", ":", "return", "self", ".", "_get_all", "(", "[", "(", "'Contents'", ",", "self", ".", "key_class", ")", ",", "(", "'CommonPr...
A lower-level method for listing contents of a bucket. This closely models the actual S3 API and requires you to manually handle the paging of results. For a higher-level method that handles the details of paging for you, you can use the list method. :type max_keys: int ...
[ "A", "lower", "-", "level", "method", "for", "listing", "contents", "of", "a", "bucket", ".", "This", "closely", "models", "the", "actual", "S3", "API", "and", "requires", "you", "to", "manually", "handle", "the", "paging", "of", "results", ".", "For", "...
python
train
46.96875
getpelican/pelican-plugins
github_activity/github_activity.py
https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/github_activity/github_activity.py#L63-L72
def register(): """ Plugin registration """ try: signals.article_generator_init.connect(feed_parser_initialization) signals.article_generator_context.connect(fetch_github_activity) except ImportError: logger.warning('`github_activity` failed to load dependency `feedparser...
[ "def", "register", "(", ")", ":", "try", ":", "signals", ".", "article_generator_init", ".", "connect", "(", "feed_parser_initialization", ")", "signals", ".", "article_generator_context", ".", "connect", "(", "fetch_github_activity", ")", "except", "ImportError", "...
Plugin registration
[ "Plugin", "registration" ]
python
train
37.7
ic-labs/django-icekit
icekit/fields.py
https://github.com/ic-labs/django-icekit/blob/c507ea5b1864303732c53ad7c5800571fca5fa94/icekit/fields.py#L54-L63
def register_model_once(cls, ModelClass, **kwargs): """ Tweaked version of `AnyUrlField.register_model` that only registers the given model after checking that it is not already registered. """ if cls._static_registry.get_for_model(ModelClass) is None: logger.warn("Mo...
[ "def", "register_model_once", "(", "cls", ",", "ModelClass", ",", "*", "*", "kwargs", ")", ":", "if", "cls", ".", "_static_registry", ".", "get_for_model", "(", "ModelClass", ")", "is", "None", ":", "logger", ".", "warn", "(", "\"Model is already registered wi...
Tweaked version of `AnyUrlField.register_model` that only registers the given model after checking that it is not already registered.
[ "Tweaked", "version", "of", "AnyUrlField", ".", "register_model", "that", "only", "registers", "the", "given", "model", "after", "checking", "that", "it", "is", "not", "already", "registered", "." ]
python
train
47.9
sloria/textblob-aptagger
textblob_aptagger/taggers.py
https://github.com/sloria/textblob-aptagger/blob/fb98bbd16a83650cab4819c4b89f0973e60fb3fe/textblob_aptagger/taggers.py#L108-L124
def _normalize(self, word): '''Normalization used in pre-processing. - All words are lower cased - Digits in the range 1800-2100 are represented as !YEAR; - Other digits are represented as !DIGITS :rtype: str ''' if '-' in word and word[0] != '-': re...
[ "def", "_normalize", "(", "self", ",", "word", ")", ":", "if", "'-'", "in", "word", "and", "word", "[", "0", "]", "!=", "'-'", ":", "return", "'!HYPHEN'", "elif", "word", ".", "isdigit", "(", ")", "and", "len", "(", "word", ")", "==", "4", ":", ...
Normalization used in pre-processing. - All words are lower cased - Digits in the range 1800-2100 are represented as !YEAR; - Other digits are represented as !DIGITS :rtype: str
[ "Normalization", "used", "in", "pre", "-", "processing", "." ]
python
train
29.411765
wandb/client
wandb/vendor/prompt_toolkit/buffer.py
https://github.com/wandb/client/blob/7d08954ed5674fee223cd85ed0d8518fe47266b2/wandb/vendor/prompt_toolkit/buffer.py#L1332-L1346
def indent(buffer, from_row, to_row, count=1): """ Indent text of a :class:`.Buffer` object. """ current_row = buffer.document.cursor_position_row line_range = range(from_row, to_row) # Apply transformation. new_text = buffer.transform_lines(line_range, lambda l: ' ' * count + l) buf...
[ "def", "indent", "(", "buffer", ",", "from_row", ",", "to_row", ",", "count", "=", "1", ")", ":", "current_row", "=", "buffer", ".", "document", ".", "cursor_position_row", "line_range", "=", "range", "(", "from_row", ",", "to_row", ")", "# Apply transformat...
Indent text of a :class:`.Buffer` object.
[ "Indent", "text", "of", "a", ":", "class", ":", ".", "Buffer", "object", "." ]
python
train
36.733333
Cue/scales
src/greplin/scales/__init__.py
https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/__init__.py#L415-L418
def update(self, instance, oldValue, newValue): """Updates the aggregate based on a change in the child value.""" self.__set__(instance, self.__get__(instance, None) + newValue - (oldValue or 0))
[ "def", "update", "(", "self", ",", "instance", ",", "oldValue", ",", "newValue", ")", ":", "self", ".", "__set__", "(", "instance", ",", "self", ".", "__get__", "(", "instance", ",", "None", ")", "+", "newValue", "-", "(", "oldValue", "or", "0", ")",...
Updates the aggregate based on a change in the child value.
[ "Updates", "the", "aggregate", "based", "on", "a", "change", "in", "the", "child", "value", "." ]
python
train
54.25
jobovy/galpy
galpy/orbit/planarOrbit.py
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/planarOrbit.py#L567-L663
def _integrateOrbit(vxvv,pot,t,method,dt): """ NAME: _integrateOrbit PURPOSE: integrate an orbit in a Phi(R) potential in the (R,phi)-plane INPUT: vxvv - array with the initial conditions stacked like [R,vR,vT,phi]; vR outward! pot - Potential instance t ...
[ "def", "_integrateOrbit", "(", "vxvv", ",", "pot", ",", "t", ",", "method", ",", "dt", ")", ":", "#First check that the potential has C", "if", "'_c'", "in", "method", ":", "if", "not", "ext_loaded", "or", "not", "_check_c", "(", "pot", ")", ":", "if", "...
NAME: _integrateOrbit PURPOSE: integrate an orbit in a Phi(R) potential in the (R,phi)-plane INPUT: vxvv - array with the initial conditions stacked like [R,vR,vT,phi]; vR outward! pot - Potential instance t - list of times at which to output (0 has to be in this...
[ "NAME", ":", "_integrateOrbit", "PURPOSE", ":", "integrate", "an", "orbit", "in", "a", "Phi", "(", "R", ")", "potential", "in", "the", "(", "R", "phi", ")", "-", "plane", "INPUT", ":", "vxvv", "-", "array", "with", "the", "initial", "conditions", "stac...
python
train
43.876289
tensorflow/tensor2tensor
tensor2tensor/layers/latent_layers.py
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/latent_layers.py#L102-L130
def ae_latent_softmax(latents_pred, latents_discrete_hot, vocab_size, hparams): """Latent prediction and loss. Args: latents_pred: Tensor of shape [..., depth]. latents_discrete_hot: Tensor of shape [..., vocab_size]. vocab_size: an int representing the vocab size. hparams: HParams. Returns: ...
[ "def", "ae_latent_softmax", "(", "latents_pred", ",", "latents_discrete_hot", ",", "vocab_size", ",", "hparams", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"latent_logits\"", ")", ":", "latents_logits", "=", "tf", ".", "layers", ".", "dense", "(", "...
Latent prediction and loss. Args: latents_pred: Tensor of shape [..., depth]. latents_discrete_hot: Tensor of shape [..., vocab_size]. vocab_size: an int representing the vocab size. hparams: HParams. Returns: sample: Tensor of shape [...], a sample from a multinomial distribution. loss: T...
[ "Latent", "prediction", "and", "loss", "." ]
python
train
42.206897
Azure/azure-multiapi-storage-python
azure/multiapi/storage/v2015_04_05/file/fileservice.py
https://github.com/Azure/azure-multiapi-storage-python/blob/bd5482547f993c6eb56fd09070e15c2e9616e440/azure/multiapi/storage/v2015_04_05/file/fileservice.py#L342-L442
def generate_file_shared_access_signature(self, share_name, directory_name=None, file_name=None, permission=None, expiry=None, ...
[ "def", "generate_file_shared_access_signature", "(", "self", ",", "share_name", ",", "directory_name", "=", "None", ",", "file_name", "=", "None", ",", "permission", "=", "None", ",", "expiry", "=", "None", ",", "start", "=", "None", ",", "id", "=", "None", ...
Generates a shared access signature for the file. Use the returned signature with the sas_token parameter of FileService. :param str share_name: Name of share. :param str directory_name: Name of directory. SAS tokens cannot be created for directories, so thi...
[ "Generates", "a", "shared", "access", "signature", "for", "the", "file", ".", "Use", "the", "returned", "signature", "with", "the", "sas_token", "parameter", "of", "FileService", "." ]
python
train
51.564356
SmokinCaterpillar/pypet
pypet/trajectory.py
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/trajectory.py#L968-L1072
def f_expand(self, build_dict, fail_safe=True): """Similar to :func:`~pypet.trajectory.Trajectory.f_explore`, but can be used to enlarge already completed trajectories. Please ensure before usage, that all explored parameters are loaded! :param build_dict: Dictionary conta...
[ "def", "f_expand", "(", "self", ",", "build_dict", ",", "fail_safe", "=", "True", ")", ":", "if", "len", "(", "self", ".", "_explored_parameters", ")", "==", "0", ":", "self", ".", "_logger", ".", "info", "(", "'Your trajectory has not been explored, yet. '", ...
Similar to :func:`~pypet.trajectory.Trajectory.f_explore`, but can be used to enlarge already completed trajectories. Please ensure before usage, that all explored parameters are loaded! :param build_dict: Dictionary containing the expansion :param fail_safe: ...
[ "Similar", "to", ":", "func", ":", "~pypet", ".", "trajectory", ".", "Trajectory", ".", "f_explore", "but", "can", "be", "used", "to", "enlarge", "already", "completed", "trajectories", "." ]
python
test
41.590476
pysal/spglm
spglm/family.py
https://github.com/pysal/spglm/blob/1339898adcb7e1638f1da83d57aa37392525f018/spglm/family.py#L866-L898
def loglike(self, endog, mu, freq_weights=1, scale=1.): r""" The log-likelihood function in terms of the fitted mean response. Parameters ---------- endog : array-like Endogenous response variable mu : array-like Fitted mean response variable ...
[ "def", "loglike", "(", "self", ",", "endog", ",", "mu", ",", "freq_weights", "=", "1", ",", "scale", "=", "1.", ")", ":", "if", "np", ".", "shape", "(", "self", ".", "n", ")", "==", "(", ")", "and", "self", ".", "n", "==", "1", ":", "return",...
r""" The log-likelihood function in terms of the fitted mean response. Parameters ---------- endog : array-like Endogenous response variable mu : array-like Fitted mean response variable freq_weights : array-like 1d array of frequency ...
[ "r", "The", "log", "-", "likelihood", "function", "in", "terms", "of", "the", "fitted", "mean", "response", "." ]
python
train
37.636364
astropy/photutils
photutils/psf/epsf.py
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/psf/epsf.py#L673-L755
def _build_epsf_step(self, stars, epsf=None): """ A single iteration of improving an ePSF. Parameters ---------- stars : `EPSFStars` object The stars used to build the ePSF. epsf : `EPSFModel` object, optional The initial ePSF model. If not inpu...
[ "def", "_build_epsf_step", "(", "self", ",", "stars", ",", "epsf", "=", "None", ")", ":", "if", "len", "(", "stars", ")", "<", "1", ":", "raise", "ValueError", "(", "'stars must contain at least one EPSFStar or '", "'LinkedEPSFStar object.'", ")", "if", "epsf", ...
A single iteration of improving an ePSF. Parameters ---------- stars : `EPSFStars` object The stars used to build the ePSF. epsf : `EPSFModel` object, optional The initial ePSF model. If not input, then the ePSF will be built from scratch. ...
[ "A", "single", "iteration", "of", "improving", "an", "ePSF", "." ]
python
train
34.963855
10gen/mongo-orchestration
mongo_orchestration/process.py
https://github.com/10gen/mongo-orchestration/blob/81fd2224205922ea2178b08190b53a33aec47261/mongo_orchestration/process.py#L161-L184
def repair_mongo(name, dbpath): """repair mongodb after usafe shutdown""" log_file = os.path.join(dbpath, 'mongod.log') cmd = [name, "--dbpath", dbpath, "--logpath", log_file, "--logappend", "--repair"] proc = subprocess.Popen( cmd, universal_newlines=True, stdout=subprocess.P...
[ "def", "repair_mongo", "(", "name", ",", "dbpath", ")", ":", "log_file", "=", "os", ".", "path", ".", "join", "(", "dbpath", ",", "'mongod.log'", ")", "cmd", "=", "[", "name", ",", "\"--dbpath\"", ",", "dbpath", ",", "\"--logpath\"", ",", "log_file", "...
repair mongodb after usafe shutdown
[ "repair", "mongodb", "after", "usafe", "shutdown" ]
python
train
41.833333
ikegami-yukino/jaconv
jaconv/jaconv.py
https://github.com/ikegami-yukino/jaconv/blob/5319e4c6b4676ab27b5e9ebec9a299d09a5a62d7/jaconv/jaconv.py#L77-L102
def kata2hira(text, ignore=''): """Convert Full-width Katakana to Hiragana Parameters ---------- text : str Full-width Katakana string. ignore : str Characters to be ignored in converting. Return ------ str Hiragana string. Examples -------- >>> pri...
[ "def", "kata2hira", "(", "text", ",", "ignore", "=", "''", ")", ":", "if", "ignore", ":", "k2h_map", "=", "_exclude_ignorechar", "(", "ignore", ",", "K2H_TABLE", ".", "copy", "(", ")", ")", "return", "_convert", "(", "text", ",", "k2h_map", ")", "retur...
Convert Full-width Katakana to Hiragana Parameters ---------- text : str Full-width Katakana string. ignore : str Characters to be ignored in converting. Return ------ str Hiragana string. Examples -------- >>> print(jaconv.kata2hira('巴マミ')) 巴まみ ...
[ "Convert", "Full", "-", "width", "Katakana", "to", "Hiragana" ]
python
train
21.307692
twilio/twilio-python
twilio/rest/api/v2010/account/usage/trigger.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/api/v2010/account/usage/trigger.py#L182-L191
def get(self, sid): """ Constructs a TriggerContext :param sid: The unique string that identifies the resource :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerContext :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext """ return Trig...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "TriggerContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
Constructs a TriggerContext :param sid: The unique string that identifies the resource :returns: twilio.rest.api.v2010.account.usage.trigger.TriggerContext :rtype: twilio.rest.api.v2010.account.usage.trigger.TriggerContext
[ "Constructs", "a", "TriggerContext" ]
python
train
39
twilio/twilio-python
twilio/rest/sync/v1/service/sync_list/sync_list_permission.py
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py#L229-L250
def fetch(self): """ Fetch a SyncListPermissionInstance :returns: Fetched SyncListPermissionInstance :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance """ params = values.of({}) payload = self._version.fetch( ...
[ "def", "fetch", "(", "self", ")", ":", "params", "=", "values", ".", "of", "(", "{", "}", ")", "payload", "=", "self", ".", "_version", ".", "fetch", "(", "'GET'", ",", "self", ".", "_uri", ",", "params", "=", "params", ",", ")", "return", "SyncL...
Fetch a SyncListPermissionInstance :returns: Fetched SyncListPermissionInstance :rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance
[ "Fetch", "a", "SyncListPermissionInstance" ]
python
train
28.318182
chaoss/grimoirelab-sigils
src/migration/to_kibana5.py
https://github.com/chaoss/grimoirelab-sigils/blob/33d395195acb316287143a535a2c6e4009bf0528/src/migration/to_kibana5.py#L86-L104
def parse_args(): """Parse arguments from the command line""" parser = argparse.ArgumentParser(description=TO_KIBANA5_DESC_MSG) parser.add_argument('-s', '--source', dest='src_path', \ required=True, help='source directory') parser.add_argument('-d', '--dest', dest='dest_path', \ requi...
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "TO_KIBANA5_DESC_MSG", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--source'", ",", "dest", "=", "'src_path'", ",", "required", "=", "T...
Parse arguments from the command line
[ "Parse", "arguments", "from", "the", "command", "line" ]
python
train
37.052632
genialis/resolwe
resolwe/flow/views/data.py
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/flow/views/data.py#L187-L213
def perform_create(self, serializer): """Create a resource.""" process = serializer.validated_data.get('process') if not process.is_active: raise exceptions.ParseError( 'Process retired (id: {}, slug: {}/{}).'.format(process.id, process.slug, process.version) ...
[ "def", "perform_create", "(", "self", ",", "serializer", ")", ":", "process", "=", "serializer", ".", "validated_data", ".", "get", "(", "'process'", ")", "if", "not", "process", ".", "is_active", ":", "raise", "exceptions", ".", "ParseError", "(", "'Process...
Create a resource.
[ "Create", "a", "resource", "." ]
python
train
44.481481
TadLeonard/tfatool
tfatool/sync.py
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L297-L304
def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): """Sync most recent file by date, time attribues""" remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f...
[ "def", "up_by_time", "(", "*", "filters", ",", "local_dir", "=", "\".\"", ",", "remote_dir", "=", "DEFAULT_REMOTE_DIR", ",", "count", "=", "1", ")", ":", "remote_files", "=", "command", ".", "map_files_raw", "(", "remote_dir", "=", "remote_dir", ")", "local_...
Sync most recent file by date, time attribues
[ "Sync", "most", "recent", "file", "by", "date", "time", "attribues" ]
python
train
56.875
VisTrails/tej
tej/submission.py
https://github.com/VisTrails/tej/blob/b8dedaeb6bdeb650b46cfe6d85e5aa9284fc7f0b/tej/submission.py#L243-L277
def _call(self, cmd, get_output): """Calls a command through the SSH connection. Remote stderr gets printed to this program's stderr. Output is captured and may be returned. """ server_err = self.server_logger() chan = self.get_client().get_transport().open_session() ...
[ "def", "_call", "(", "self", ",", "cmd", ",", "get_output", ")", ":", "server_err", "=", "self", ".", "server_logger", "(", ")", "chan", "=", "self", ".", "get_client", "(", ")", ".", "get_transport", "(", ")", ".", "open_session", "(", ")", "try", "...
Calls a command through the SSH connection. Remote stderr gets printed to this program's stderr. Output is captured and may be returned.
[ "Calls", "a", "command", "through", "the", "SSH", "connection", "." ]
python
train
37.314286
fitnr/convertdate
convertdate/french_republican.py
https://github.com/fitnr/convertdate/blob/e920f168a87f99183b0aa7290d6c3af222582d43/convertdate/french_republican.py#L291-L300
def _from_jd_equinox(jd): '''Calculate the FR day using the equinox as day 1''' jd = trunc(jd) + 0.5 equinoxe = premier_da_la_annee(jd) an = gregorian.from_jd(equinoxe)[0] - YEAR_EPOCH mois = trunc((jd - equinoxe) / 30.) + 1 jour = int((jd - equinoxe) % 30) + 1 return (an, mois, jour)
[ "def", "_from_jd_equinox", "(", "jd", ")", ":", "jd", "=", "trunc", "(", "jd", ")", "+", "0.5", "equinoxe", "=", "premier_da_la_annee", "(", "jd", ")", "an", "=", "gregorian", ".", "from_jd", "(", "equinoxe", ")", "[", "0", "]", "-", "YEAR_EPOCH", "m...
Calculate the FR day using the equinox as day 1
[ "Calculate", "the", "FR", "day", "using", "the", "equinox", "as", "day", "1" ]
python
train
30.6
svasilev94/GraphLibrary
graphlibrary/first_search.py
https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/first_search.py#L35-L51
def BFS_Tree(G, start): """ Return an oriented tree constructed from bfs starting at 'start'. """ if start not in G.vertices: raise GraphInsertError("Vertex %s doesn't exist." % (start,)) pred = BFS(G, start) T = digraph.DiGraph() queue = Queue() queue.put(start) wh...
[ "def", "BFS_Tree", "(", "G", ",", "start", ")", ":", "if", "start", "not", "in", "G", ".", "vertices", ":", "raise", "GraphInsertError", "(", "\"Vertex %s doesn't exist.\"", "%", "(", "start", ",", ")", ")", "pred", "=", "BFS", "(", "G", ",", "start", ...
Return an oriented tree constructed from bfs starting at 'start'.
[ "Return", "an", "oriented", "tree", "constructed", "from", "bfs", "starting", "at", "start", "." ]
python
train
30.882353
moliware/dicts
dicts/sorteddict.py
https://github.com/moliware/dicts/blob/0e8258cc3dc00fe929685cae9cda062222722715/dicts/sorteddict.py#L35-L40
def iteritems(self): """ Sort and then iterate the dictionary """ sorted_data = sorted(self.data.iteritems(), self.cmp, self.key, self.reverse) for k,v in sorted_data: yield k,v
[ "def", "iteritems", "(", "self", ")", ":", "sorted_data", "=", "sorted", "(", "self", ".", "data", ".", "iteritems", "(", ")", ",", "self", ".", "cmp", ",", "self", ".", "key", ",", "self", ".", "reverse", ")", "for", "k", ",", "v", "in", "sorted...
Sort and then iterate the dictionary
[ "Sort", "and", "then", "iterate", "the", "dictionary" ]
python
train
39.5
googleapis/google-cloud-python
spanner/google/cloud/spanner_v1/param_types.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/spanner/google/cloud/spanner_v1/param_types.py#L57-L68
def Struct(fields): # pylint: disable=invalid-name """Construct a struct parameter type description protobuf. :type fields: list of :class:`type_pb2.StructType.Field` :param fields: the fields of the struct :rtype: :class:`type_pb2.Type` :returns: the appropriate struct-type protobuf """ ...
[ "def", "Struct", "(", "fields", ")", ":", "# pylint: disable=invalid-name", "return", "type_pb2", ".", "Type", "(", "code", "=", "type_pb2", ".", "STRUCT", ",", "struct_type", "=", "type_pb2", ".", "StructType", "(", "fields", "=", "fields", ")", ")" ]
Construct a struct parameter type description protobuf. :type fields: list of :class:`type_pb2.StructType.Field` :param fields: the fields of the struct :rtype: :class:`type_pb2.Type` :returns: the appropriate struct-type protobuf
[ "Construct", "a", "struct", "parameter", "type", "description", "protobuf", "." ]
python
train
34.416667
raphaelm/python-fints
fints/client.py
https://github.com/raphaelm/python-fints/blob/fee55ae37d3182d0adb40507d4acb98b06057e4a/fints/client.py#L947-L959
def get_data(self) -> bytes: """Return a compressed datablob representing this object. To restore the object, use :func:`fints.client.NeedRetryResponse.from_data`. """ data = { "_class_name": self.__class__.__name__, "version": 1, "segments_bi...
[ "def", "get_data", "(", "self", ")", "->", "bytes", ":", "data", "=", "{", "\"_class_name\"", ":", "self", ".", "__class__", ".", "__name__", ",", "\"version\"", ":", "1", ",", "\"segments_bin\"", ":", "SegmentSequence", "(", "[", "self", ".", "command_seg...
Return a compressed datablob representing this object. To restore the object, use :func:`fints.client.NeedRetryResponse.from_data`.
[ "Return", "a", "compressed", "datablob", "representing", "this", "object", ".", "To", "restore", "the", "object", "use", ":", "func", ":", "fints", ".", "client", ".", "NeedRetryResponse", ".", "from_data", "." ]
python
train
44
michael-lazar/rtv
rtv/packages/praw/__init__.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L1090-L1109
def get_submission(self, url=None, submission_id=None, comment_limit=0, comment_sort=None, params=None): """Return a Submission object for the given url or submission_id. :param comment_limit: The desired number of comments to fetch. If <= 0 fetch the default number f...
[ "def", "get_submission", "(", "self", ",", "url", "=", "None", ",", "submission_id", "=", "None", ",", "comment_limit", "=", "0", ",", "comment_sort", "=", "None", ",", "params", "=", "None", ")", ":", "if", "bool", "(", "url", ")", "==", "bool", "("...
Return a Submission object for the given url or submission_id. :param comment_limit: The desired number of comments to fetch. If <= 0 fetch the default number for the session's user. If None, fetch the maximum possible. :param comment_sort: The sort order for retrieved comments....
[ "Return", "a", "Submission", "object", "for", "the", "given", "url", "or", "submission_id", "." ]
python
train
53.05
BreakingBytes/simkit
simkit/core/outputs.py
https://github.com/BreakingBytes/simkit/blob/205163d879d3880b6c9ef609f1b723a58773026b/simkit/core/outputs.py#L31-L52
def register(self, new_outputs, *args, **kwargs): """ Register outputs and metadata. * ``initial_value`` - used in dynamic calculations * ``size`` - number of elements per timestep * ``uncertainty`` - in percent of nominal value * ``variance`` - dictionary of covariances...
[ "def", "register", "(", "self", ",", "new_outputs", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "zip", "(", "self", ".", "meta_names", ",", "args", ")", ")", "# call super method", "super", "(", "OutputRegistry", ...
Register outputs and metadata. * ``initial_value`` - used in dynamic calculations * ``size`` - number of elements per timestep * ``uncertainty`` - in percent of nominal value * ``variance`` - dictionary of covariances, diagonal is square of uncertianties, no units * ``...
[ "Register", "outputs", "and", "metadata", "." ]
python
train
44.272727
ensime/ensime-vim
ensime_shared/protocol.py
https://github.com/ensime/ensime-vim/blob/caa734e84f002b25446c615706283a74edd4ecfe/ensime_shared/protocol.py#L163-L177
def handle_symbol_search(self, call_id, payload): """Handler for symbol search results""" self.log.debug('handle_symbol_search: in %s', Pretty(payload)) syms = payload["syms"] qfList = [] for sym in syms: p = sym.get("pos") if p: item = se...
[ "def", "handle_symbol_search", "(", "self", ",", "call_id", ",", "payload", ")", ":", "self", ".", "log", ".", "debug", "(", "'handle_symbol_search: in %s'", ",", "Pretty", "(", "payload", ")", ")", "syms", "=", "payload", "[", "\"syms\"", "]", "qfList", "...
Handler for symbol search results
[ "Handler", "for", "symbol", "search", "results" ]
python
train
42.8