repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Display/RPiDisplay.py
RPiDiaplay.clear
def clear(self, fill = 0x00): """! Clear buffer data and other data RPiDiaplay object just implemented clear buffer data """ self._buffer = [ fill ] * ( self.width * self.height )
python
def clear(self, fill = 0x00): """! Clear buffer data and other data RPiDiaplay object just implemented clear buffer data """ self._buffer = [ fill ] * ( self.width * self.height )
[ "def", "clear", "(", "self", ",", "fill", "=", "0x00", ")", ":", "self", ".", "_buffer", "=", "[", "fill", "]", "*", "(", "self", ".", "width", "*", "self", ".", "height", ")" ]
! Clear buffer data and other data RPiDiaplay object just implemented clear buffer data
[ "!", "Clear", "buffer", "data", "and", "other", "data", "RPiDiaplay", "object", "just", "implemented", "clear", "buffer", "data" ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Display/RPiDisplay.py#L116-L121
train
57,300
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.connect
def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 ...
python
def connect(self): """This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection """ count = 1 ...
[ "def", "connect", "(", "self", ")", ":", "count", "=", "1", "no_of_servers", "=", "len", "(", "self", ".", "_rabbit_urls", ")", "while", "True", ":", "server_choice", "=", "(", "count", "%", "no_of_servers", ")", "-", "1", "self", ".", "_url", "=", "...
This method connects to RabbitMQ using a SelectConnection object, returning the connection handle. When the connection is established, the on_connection_open method will be invoked by pika. :rtype: pika.SelectConnection
[ "This", "method", "connects", "to", "RabbitMQ", "using", "a", "SelectConnection", "object", "returning", "the", "connection", "handle", "." ]
985adfdb09cf1b263a1f311438baeb42cbcb503a
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L58-L88
train
57,301
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
AsyncConsumer.nack_message
def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag)
python
def nack_message(self, delivery_tag, **kwargs): """Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame """ logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs) self._channel.basic_nack(delivery_tag)
[ "def", "nack_message", "(", "self", ",", "delivery_tag", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "info", "(", "'Nacking message'", ",", "delivery_tag", "=", "delivery_tag", ",", "*", "*", "kwargs", ")", "self", ".", "_channel", ".", "basic_nack",...
Negative acknowledge a message :param int delivery_tag: The deliver tag from the Basic.Deliver frame
[ "Negative", "acknowledge", "a", "message" ]
985adfdb09cf1b263a1f311438baeb42cbcb503a
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L266-L273
train
57,302
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
MessageConsumer.tx_id
def tx_id(properties): """ Gets the tx_id for a message from a rabbit queue, using the message properties. Will raise KeyError if tx_id is missing from message headers. : param properties: Message properties : returns: tx_id of survey response : rtype: str ...
python
def tx_id(properties): """ Gets the tx_id for a message from a rabbit queue, using the message properties. Will raise KeyError if tx_id is missing from message headers. : param properties: Message properties : returns: tx_id of survey response : rtype: str ...
[ "def", "tx_id", "(", "properties", ")", ":", "tx_id", "=", "properties", ".", "headers", "[", "'tx_id'", "]", "logger", ".", "info", "(", "\"Retrieved tx_id from message properties: tx_id={}\"", ".", "format", "(", "tx_id", ")", ")", "return", "tx_id" ]
Gets the tx_id for a message from a rabbit queue, using the message properties. Will raise KeyError if tx_id is missing from message headers. : param properties: Message properties : returns: tx_id of survey response : rtype: str
[ "Gets", "the", "tx_id", "for", "a", "message", "from", "a", "rabbit", "queue", "using", "the", "message", "properties", ".", "Will", "raise", "KeyError", "if", "tx_id", "is", "missing", "from", "message", "headers", "." ]
985adfdb09cf1b263a1f311438baeb42cbcb503a
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L444-L457
train
57,303
ONSdigital/sdc-rabbit
sdc/rabbit/consumers.py
MessageConsumer.on_message
def on_message(self, unused_channel, basic_deliver, properties, body): """Called on receipt of a message from a queue. Processes the message using the self._process method or function and positively acknowledges the queue if successful. If processing is not succesful, the message can ei...
python
def on_message(self, unused_channel, basic_deliver, properties, body): """Called on receipt of a message from a queue. Processes the message using the self._process method or function and positively acknowledges the queue if successful. If processing is not succesful, the message can ei...
[ "def", "on_message", "(", "self", ",", "unused_channel", ",", "basic_deliver", ",", "properties", ",", "body", ")", ":", "if", "self", ".", "check_tx_id", ":", "try", ":", "tx_id", "=", "self", ".", "tx_id", "(", "properties", ")", "logger", ".", "info",...
Called on receipt of a message from a queue. Processes the message using the self._process method or function and positively acknowledges the queue if successful. If processing is not succesful, the message can either be rejected, quarantined or negatively acknowledged, depending on the...
[ "Called", "on", "receipt", "of", "a", "message", "from", "a", "queue", "." ]
985adfdb09cf1b263a1f311438baeb42cbcb503a
https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L500-L580
train
57,304
objectrocket/python-client
objectrocket/auth.py
Auth.authenticate
def authenticate(self, username, password): """Authenticate against the ObjectRocket API. :param str username: The username to perform basic authentication against the API with. :param str password: The password to perform basic authentication against the API with. :returns: A token use...
python
def authenticate(self, username, password): """Authenticate against the ObjectRocket API. :param str username: The username to perform basic authentication against the API with. :param str password: The password to perform basic authentication against the API with. :returns: A token use...
[ "def", "authenticate", "(", "self", ",", "username", ",", "password", ")", ":", "# Update the username and password bound to this instance for re-authentication needs.", "self", ".", "_username", "=", "username", "self", ".", "_password", "=", "password", "# Attempt to auth...
Authenticate against the ObjectRocket API. :param str username: The username to perform basic authentication against the API with. :param str password: The password to perform basic authentication against the API with. :returns: A token used for authentication against token protected resources....
[ "Authenticate", "against", "the", "ObjectRocket", "API", "." ]
a65868c7511ff49a5fbe304e53bf592b7fc6d5ef
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/auth.py#L27-L66
train
57,305
objectrocket/python-client
objectrocket/auth.py
Auth._refresh
def _refresh(self): """Refresh the API token using the currently bound credentials. This is simply a convenience method to be invoked automatically if authentication fails during normal client use. """ # Request and set a new API token. new_token = self.authenticate(self...
python
def _refresh(self): """Refresh the API token using the currently bound credentials. This is simply a convenience method to be invoked automatically if authentication fails during normal client use. """ # Request and set a new API token. new_token = self.authenticate(self...
[ "def", "_refresh", "(", "self", ")", ":", "# Request and set a new API token.", "new_token", "=", "self", ".", "authenticate", "(", "self", ".", "_username", ",", "self", ".", "_password", ")", "self", ".", "_token", "=", "new_token", "logger", ".", "info", ...
Refresh the API token using the currently bound credentials. This is simply a convenience method to be invoked automatically if authentication fails during normal client use.
[ "Refresh", "the", "API", "token", "using", "the", "currently", "bound", "credentials", "." ]
a65868c7511ff49a5fbe304e53bf592b7fc6d5ef
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/auth.py#L86-L96
train
57,306
objectrocket/python-client
objectrocket/auth.py
Auth._verify
def _verify(self, token): """Verify that the given token is valid. :param str token: The API token to verify. :returns: The token's corresponding user model as a dict, or None if invalid. :rtype: dict """ # Attempt to authenticate. url = '{}{}/'.format(self._url,...
python
def _verify(self, token): """Verify that the given token is valid. :param str token: The API token to verify. :returns: The token's corresponding user model as a dict, or None if invalid. :rtype: dict """ # Attempt to authenticate. url = '{}{}/'.format(self._url,...
[ "def", "_verify", "(", "self", ",", "token", ")", ":", "# Attempt to authenticate.", "url", "=", "'{}{}/'", ".", "format", "(", "self", ".", "_url", ",", "'verify'", ")", "resp", "=", "requests", ".", "post", "(", "url", ",", "json", "=", "{", "'token'...
Verify that the given token is valid. :param str token: The API token to verify. :returns: The token's corresponding user model as a dict, or None if invalid. :rtype: dict
[ "Verify", "that", "the", "given", "token", "is", "valid", "." ]
a65868c7511ff49a5fbe304e53bf592b7fc6d5ef
https://github.com/objectrocket/python-client/blob/a65868c7511ff49a5fbe304e53bf592b7fc6d5ef/objectrocket/auth.py#L124-L140
train
57,307
wdbm/abstraction
es-1.py
preprocess
def preprocess(net, image): ''' convert to Caffe input image layout ''' return np.float32(np.rollaxis(image, 2)[::-1]) - net.transformer.mean["data"]
python
def preprocess(net, image): ''' convert to Caffe input image layout ''' return np.float32(np.rollaxis(image, 2)[::-1]) - net.transformer.mean["data"]
[ "def", "preprocess", "(", "net", ",", "image", ")", ":", "return", "np", ".", "float32", "(", "np", ".", "rollaxis", "(", "image", ",", "2", ")", "[", ":", ":", "-", "1", "]", ")", "-", "net", ".", "transformer", ".", "mean", "[", "\"data\"", "...
convert to Caffe input image layout
[ "convert", "to", "Caffe", "input", "image", "layout" ]
58c81e73954cc6b4cd2f79b2216467528a96376b
https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/es-1.py#L65-L69
train
57,308
wdbm/abstraction
es-1.py
make_step
def make_step( net, step_size = 1.5, end = "inception_4c/output", jitter = 32, clip = True, objective = objective_L2 ): ''' basic gradient ascent step ''' src = net.blobs["data"] dst = net.blobs[end] ox, oy = np.random.randint(- jitter, jitter + 1, 2)...
python
def make_step( net, step_size = 1.5, end = "inception_4c/output", jitter = 32, clip = True, objective = objective_L2 ): ''' basic gradient ascent step ''' src = net.blobs["data"] dst = net.blobs[end] ox, oy = np.random.randint(- jitter, jitter + 1, 2)...
[ "def", "make_step", "(", "net", ",", "step_size", "=", "1.5", ",", "end", "=", "\"inception_4c/output\"", ",", "jitter", "=", "32", ",", "clip", "=", "True", ",", "objective", "=", "objective_L2", ")", ":", "src", "=", "net", ".", "blobs", "[", "\"data...
basic gradient ascent step
[ "basic", "gradient", "ascent", "step" ]
58c81e73954cc6b4cd2f79b2216467528a96376b
https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/es-1.py#L83-L114
train
57,309
wdbm/abstraction
es-1.py
deepdream
def deepdream( net, base_image, iter_n = 10, octave_n = 4, octave_scale = 1.4, end = "inception_4c/output", clip = True, **step_params ): ''' an ascent through different scales called "octaves" ''' # Prepare base images for all octaves....
python
def deepdream( net, base_image, iter_n = 10, octave_n = 4, octave_scale = 1.4, end = "inception_4c/output", clip = True, **step_params ): ''' an ascent through different scales called "octaves" ''' # Prepare base images for all octaves....
[ "def", "deepdream", "(", "net", ",", "base_image", ",", "iter_n", "=", "10", ",", "octave_n", "=", "4", ",", "octave_scale", "=", "1.4", ",", "end", "=", "\"inception_4c/output\"", ",", "clip", "=", "True", ",", "*", "*", "step_params", ")", ":", "# Pr...
an ascent through different scales called "octaves"
[ "an", "ascent", "through", "different", "scales", "called", "octaves" ]
58c81e73954cc6b4cd2f79b2216467528a96376b
https://github.com/wdbm/abstraction/blob/58c81e73954cc6b4cd2f79b2216467528a96376b/es-1.py#L117-L175
train
57,310
jkitzes/macroeco
macroeco/main/_main.py
main
def main(param_path='parameters.txt'): """ Entry point function for analysis based on parameter files. Parameters ---------- param_path : str Path to user-generated parameter file """ # Confirm parameters file is present if not os.path.isfile(param_path): raise IOError...
python
def main(param_path='parameters.txt'): """ Entry point function for analysis based on parameter files. Parameters ---------- param_path : str Path to user-generated parameter file """ # Confirm parameters file is present if not os.path.isfile(param_path): raise IOError...
[ "def", "main", "(", "param_path", "=", "'parameters.txt'", ")", ":", "# Confirm parameters file is present", "if", "not", "os", ".", "path", ".", "isfile", "(", "param_path", ")", ":", "raise", "IOError", ",", "\"Parameter file not found at %s\"", "%", "param_path",...
Entry point function for analysis based on parameter files. Parameters ---------- param_path : str Path to user-generated parameter file
[ "Entry", "point", "function", "for", "analysis", "based", "on", "parameter", "files", "." ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/main/_main.py#L29-L96
train
57,311
jkitzes/macroeco
macroeco/main/_main.py
_do_analysis
def _do_analysis(options): """ Do analysis for a single run, as specified by options. Parameters ---------- options : dict Option names and values for analysis """ module = _function_location(options) core_results = _call_analysis_function(options, module) if module == 'e...
python
def _do_analysis(options): """ Do analysis for a single run, as specified by options. Parameters ---------- options : dict Option names and values for analysis """ module = _function_location(options) core_results = _call_analysis_function(options, module) if module == 'e...
[ "def", "_do_analysis", "(", "options", ")", ":", "module", "=", "_function_location", "(", "options", ")", "core_results", "=", "_call_analysis_function", "(", "options", ",", "module", ")", "if", "module", "==", "'emp'", "and", "(", "'models'", "in", "options...
Do analysis for a single run, as specified by options. Parameters ---------- options : dict Option names and values for analysis
[ "Do", "analysis", "for", "a", "single", "run", "as", "specified", "by", "options", "." ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/main/_main.py#L141-L160
train
57,312
jkitzes/macroeco
macroeco/main/_main.py
_call_analysis_function
def _call_analysis_function(options, module): """ Call function from module and get result, using inputs from options Parameters ---------- options : dict Option names and values for analysis module : str Short name of module within macroeco containing analysis function Ret...
python
def _call_analysis_function(options, module): """ Call function from module and get result, using inputs from options Parameters ---------- options : dict Option names and values for analysis module : str Short name of module within macroeco containing analysis function Ret...
[ "def", "_call_analysis_function", "(", "options", ",", "module", ")", ":", "args", ",", "kwargs", "=", "_get_args_kwargs", "(", "options", ",", "module", ")", "return", "eval", "(", "\"%s.%s(*args, **kwargs)\"", "%", "(", "module", ",", "options", "[", "'analy...
Call function from module and get result, using inputs from options Parameters ---------- options : dict Option names and values for analysis module : str Short name of module within macroeco containing analysis function Returns ------- dataframe, array, value, list of tupl...
[ "Call", "function", "from", "module", "and", "get", "result", "using", "inputs", "from", "options" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/main/_main.py#L180-L202
train
57,313
jkitzes/macroeco
macroeco/main/_main.py
_emp_extra_options
def _emp_extra_options(options): """ Get special options patch, cols, and splits if analysis in emp module """ # Check that metadata is valid metadata_path = os.path.normpath(os.path.join(options['param_dir'], options['metadata'])) if not os.pat...
python
def _emp_extra_options(options): """ Get special options patch, cols, and splits if analysis in emp module """ # Check that metadata is valid metadata_path = os.path.normpath(os.path.join(options['param_dir'], options['metadata'])) if not os.pat...
[ "def", "_emp_extra_options", "(", "options", ")", ":", "# Check that metadata is valid", "metadata_path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "options", "[", "'param_dir'", "]", ",", "options", "[", "'metadata'", ...
Get special options patch, cols, and splits if analysis in emp module
[ "Get", "special", "options", "patch", "cols", "and", "splits", "if", "analysis", "in", "emp", "module" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/main/_main.py#L249-L272
train
57,314
jkitzes/macroeco
macroeco/main/_main.py
_fit_models
def _fit_models(options, core_results): """ Fit models to empirical result from a function in emp module Parameters ---------- options : dict Option names and values for analysis core_results : list of tuples Output of function in emp Returns ------- list of dicts ...
python
def _fit_models(options, core_results): """ Fit models to empirical result from a function in emp module Parameters ---------- options : dict Option names and values for analysis core_results : list of tuples Output of function in emp Returns ------- list of dicts ...
[ "def", "_fit_models", "(", "options", ",", "core_results", ")", ":", "logging", ".", "info", "(", "\"Fitting models\"", ")", "models", "=", "options", "[", "'models'", "]", ".", "replace", "(", "' '", ",", "''", ")", ".", "split", "(", "';'", ")", "# T...
Fit models to empirical result from a function in emp module Parameters ---------- options : dict Option names and values for analysis core_results : list of tuples Output of function in emp Returns ------- list of dicts Each element in list corresponds to a subset....
[ "Fit", "models", "to", "empirical", "result", "from", "a", "function", "in", "emp", "module" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/main/_main.py#L302-L345
train
57,315
jkitzes/macroeco
macroeco/main/_main.py
_save_results
def _save_results(options, module, core_results, fit_results): """ Save results of analysis as tables and figures Parameters ---------- options : dict Option names and values for analysis module : str Module that contained function used to generate core_results core_results ...
python
def _save_results(options, module, core_results, fit_results): """ Save results of analysis as tables and figures Parameters ---------- options : dict Option names and values for analysis module : str Module that contained function used to generate core_results core_results ...
[ "def", "_save_results", "(", "options", ",", "module", ",", "core_results", ",", "fit_results", ")", ":", "logging", ".", "info", "(", "\"Saving all results\"", ")", "# Use custom plot format", "mpl", ".", "rcParams", ".", "update", "(", "misc", ".", "rcparams",...
Save results of analysis as tables and figures Parameters ---------- options : dict Option names and values for analysis module : str Module that contained function used to generate core_results core_results : dataframe, array, value, list of tuples Results of main analysis ...
[ "Save", "results", "of", "analysis", "as", "tables", "and", "figures" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/main/_main.py#L398-L437
train
57,316
jkitzes/macroeco
macroeco/main/_main.py
_write_subset_index_file
def _write_subset_index_file(options, core_results): """ Write table giving index of subsets, giving number and subset string """ f_path = os.path.join(options['run_dir'], '_subset_index.csv') subset_strs = zip(*core_results)[0] index = np.arange(len(subset_strs)) + 1 df = pd.DataFrame({'su...
python
def _write_subset_index_file(options, core_results): """ Write table giving index of subsets, giving number and subset string """ f_path = os.path.join(options['run_dir'], '_subset_index.csv') subset_strs = zip(*core_results)[0] index = np.arange(len(subset_strs)) + 1 df = pd.DataFrame({'su...
[ "def", "_write_subset_index_file", "(", "options", ",", "core_results", ")", ":", "f_path", "=", "os", ".", "path", ".", "join", "(", "options", "[", "'run_dir'", "]", ",", "'_subset_index.csv'", ")", "subset_strs", "=", "zip", "(", "*", "core_results", ")",...
Write table giving index of subsets, giving number and subset string
[ "Write", "table", "giving", "index", "of", "subsets", "giving", "number", "and", "subset", "string" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/main/_main.py#L474-L483
train
57,317
jkitzes/macroeco
macroeco/main/_main.py
_pad_plot_frame
def _pad_plot_frame(ax, pad=0.01): """ Provides padding on sides of frame equal to pad fraction of plot """ xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() xr = xmax - xmin yr = ymax - ymin ax.set_xlim(xmin - xr*pad, xmax + xr*pad) ax.set_ylim(ymin - yr*pad, ymax + yr*pad) ...
python
def _pad_plot_frame(ax, pad=0.01): """ Provides padding on sides of frame equal to pad fraction of plot """ xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() xr = xmax - xmin yr = ymax - ymin ax.set_xlim(xmin - xr*pad, xmax + xr*pad) ax.set_ylim(ymin - yr*pad, ymax + yr*pad) ...
[ "def", "_pad_plot_frame", "(", "ax", ",", "pad", "=", "0.01", ")", ":", "xmin", ",", "xmax", "=", "ax", ".", "get_xlim", "(", ")", "ymin", ",", "ymax", "=", "ax", ".", "get_ylim", "(", ")", "xr", "=", "xmax", "-", "xmin", "yr", "=", "ymax", "-"...
Provides padding on sides of frame equal to pad fraction of plot
[ "Provides", "padding", "on", "sides", "of", "frame", "equal", "to", "pad", "fraction", "of", "plot" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/main/_main.py#L593-L606
train
57,318
jkitzes/macroeco
macroeco/main/_main.py
_output_cdf_plot
def _output_cdf_plot(core_result, spid, models, options, fit_results): """Function for plotting cdf""" # CDF x = core_result['y'].values df = emp.empirical_cdf(x) df.columns = ['x', 'empirical'] def calc_func(model, df, shapes): return eval("mod.%s.cdf(df['x'], *shapes)" % model) ...
python
def _output_cdf_plot(core_result, spid, models, options, fit_results): """Function for plotting cdf""" # CDF x = core_result['y'].values df = emp.empirical_cdf(x) df.columns = ['x', 'empirical'] def calc_func(model, df, shapes): return eval("mod.%s.cdf(df['x'], *shapes)" % model) ...
[ "def", "_output_cdf_plot", "(", "core_result", ",", "spid", ",", "models", ",", "options", ",", "fit_results", ")", ":", "# CDF", "x", "=", "core_result", "[", "'y'", "]", ".", "values", "df", "=", "emp", ".", "empirical_cdf", "(", "x", ")", "df", ".",...
Function for plotting cdf
[ "Function", "for", "plotting", "cdf" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/main/_main.py#L609-L623
train
57,319
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Attitude/MPU6050.py
MPU6050.openOnlyAccel
def openOnlyAccel(self, cycleFreq = 0x00 ): """! Trun on device into Accelerometer Only Low Power Mode @param cycleFreq can be choise: @see VAL_PWR_MGMT_2_LP_WAKE_CTRL_1_25HZ is default @see VAL_PWR_MGMT_2_LP_WAKE_CTRL_5HZ @see VAL_PWR_MGMT_2_LP_WAKE_CTRL_20H...
python
def openOnlyAccel(self, cycleFreq = 0x00 ): """! Trun on device into Accelerometer Only Low Power Mode @param cycleFreq can be choise: @see VAL_PWR_MGMT_2_LP_WAKE_CTRL_1_25HZ is default @see VAL_PWR_MGMT_2_LP_WAKE_CTRL_5HZ @see VAL_PWR_MGMT_2_LP_WAKE_CTRL_20H...
[ "def", "openOnlyAccel", "(", "self", ",", "cycleFreq", "=", "0x00", ")", ":", "self", ".", "openWith", "(", "accel", "=", "True", ",", "gyro", "=", "False", ",", "temp", "=", "False", ",", "cycle", "=", "True", ",", "cycleFreq", "=", "cycleFreq", ")"...
! Trun on device into Accelerometer Only Low Power Mode @param cycleFreq can be choise: @see VAL_PWR_MGMT_2_LP_WAKE_CTRL_1_25HZ is default @see VAL_PWR_MGMT_2_LP_WAKE_CTRL_5HZ @see VAL_PWR_MGMT_2_LP_WAKE_CTRL_20HZ @see VAL_PWR_MGMT_2_LP_WAKE_CTRL_40HZ
[ "!", "Trun", "on", "device", "into", "Accelerometer", "Only", "Low", "Power", "Mode" ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Attitude/MPU6050.py#L272-L281
train
57,320
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Attitude/MPU6050.py
MPU6050.setMotionInt
def setMotionInt(self, motDHPF = 0x01, motTHR = 0x14, motDUR = 0x30, motDeteDec = 0x15 ): """! Set to enable Motion Detection Interrupt @param motDHPF Set the Digital High Pass Filter. Default is 0x01 (5Hz) @param motTHR Desired motion threshold. Default is 20 (0x14) @param mot...
python
def setMotionInt(self, motDHPF = 0x01, motTHR = 0x14, motDUR = 0x30, motDeteDec = 0x15 ): """! Set to enable Motion Detection Interrupt @param motDHPF Set the Digital High Pass Filter. Default is 0x01 (5Hz) @param motTHR Desired motion threshold. Default is 20 (0x14) @param mot...
[ "def", "setMotionInt", "(", "self", ",", "motDHPF", "=", "0x01", ",", "motTHR", "=", "0x14", ",", "motDUR", "=", "0x30", ",", "motDeteDec", "=", "0x15", ")", ":", "#After power on (0x00 to register (decimal) 107), the Motion Detection Interrupt can be enabled as follows:"...
! Set to enable Motion Detection Interrupt @param motDHPF Set the Digital High Pass Filter. Default is 0x01 (5Hz) @param motTHR Desired motion threshold. Default is 20 (0x14) @param motDUR Desired motion duration. Default is 48ms (0x30) @param motDeteDec Motion detection decre...
[ "!", "Set", "to", "enable", "Motion", "Detection", "Interrupt" ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Attitude/MPU6050.py#L290-L346
train
57,321
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Attitude/MPU6050.py
MPU6050.readAccelRange
def readAccelRange( self ): """! Reads the range of accelerometer setup. @return an int value. It should be one of the following values: @see ACCEL_RANGE_2G @see ACCEL_RANGE_4G @see ACCEL_RANGE_8G @see ACCEL_RANGE_16G ...
python
def readAccelRange( self ): """! Reads the range of accelerometer setup. @return an int value. It should be one of the following values: @see ACCEL_RANGE_2G @see ACCEL_RANGE_4G @see ACCEL_RANGE_8G @see ACCEL_RANGE_16G ...
[ "def", "readAccelRange", "(", "self", ")", ":", "raw_data", "=", "self", ".", "_readByte", "(", "self", ".", "REG_ACCEL_CONFIG", ")", "raw_data", "=", "(", "raw_data", "|", "0xE7", ")", "^", "0xE7", "return", "raw_data" ]
! Reads the range of accelerometer setup. @return an int value. It should be one of the following values: @see ACCEL_RANGE_2G @see ACCEL_RANGE_4G @see ACCEL_RANGE_8G @see ACCEL_RANGE_16G
[ "!", "Reads", "the", "range", "of", "accelerometer", "setup", "." ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Attitude/MPU6050.py#L414-L427
train
57,322
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Attitude/MPU6050.py
MPU6050.getAccelData
def getAccelData( self, raw = False ): """! Gets and returns the X, Y and Z values from the accelerometer. @param raw If raw is True, it will return the data in m/s^2,<br> If raw is False, it will return the data in g @return a dictionary with the measurement results or Boolean. ...
python
def getAccelData( self, raw = False ): """! Gets and returns the X, Y and Z values from the accelerometer. @param raw If raw is True, it will return the data in m/s^2,<br> If raw is False, it will return the data in g @return a dictionary with the measurement results or Boolean. ...
[ "def", "getAccelData", "(", "self", ",", "raw", "=", "False", ")", ":", "x", "=", "self", ".", "_readWord", "(", "self", ".", "REG_ACCEL_XOUT_H", ")", "y", "=", "self", ".", "_readWord", "(", "self", ".", "REG_ACCEL_YOUT_H", ")", "z", "=", "self", "....
! Gets and returns the X, Y and Z values from the accelerometer. @param raw If raw is True, it will return the data in m/s^2,<br> If raw is False, it will return the data in g @return a dictionary with the measurement results or Boolean. @retval {...} data in m/s^2 if raw is True. ...
[ "!", "Gets", "and", "returns", "the", "X", "Y", "and", "Z", "values", "from", "the", "accelerometer", "." ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Attitude/MPU6050.py#L429-L467
train
57,323
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Attitude/MPU6050.py
MPU6050.readGyroRange
def readGyroRange( self ): """! Read range of gyroscope. @return an int value. It should be one of the following values (GYRO_RANGE_250DEG) @see GYRO_RANGE_250DEG @see GYRO_RANGE_500DEG @see GYRO_RANGE_1KDEG @see GYRO_RANGE_2KDEG """ raw_data = s...
python
def readGyroRange( self ): """! Read range of gyroscope. @return an int value. It should be one of the following values (GYRO_RANGE_250DEG) @see GYRO_RANGE_250DEG @see GYRO_RANGE_500DEG @see GYRO_RANGE_1KDEG @see GYRO_RANGE_2KDEG """ raw_data = s...
[ "def", "readGyroRange", "(", "self", ")", ":", "raw_data", "=", "self", ".", "_readByte", "(", "self", ".", "REG_GYRO_CONFIG", ")", "raw_data", "=", "(", "raw_data", "|", "0xE7", ")", "^", "0xE7", "return", "raw_data" ]
! Read range of gyroscope. @return an int value. It should be one of the following values (GYRO_RANGE_250DEG) @see GYRO_RANGE_250DEG @see GYRO_RANGE_500DEG @see GYRO_RANGE_1KDEG @see GYRO_RANGE_2KDEG
[ "!", "Read", "range", "of", "gyroscope", "." ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Attitude/MPU6050.py#L483-L496
train
57,324
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Attitude/MPU6050.py
MPU6050.getGyroData
def getGyroData(self): """! Gets and returns the X, Y and Z values from the gyroscope @return a dictionary with the measurement results or Boolean. @retval {...} a dictionary data. @retval False means 'Unkown gyroscope range', that you need to check the "gyroscope range"...
python
def getGyroData(self): """! Gets and returns the X, Y and Z values from the gyroscope @return a dictionary with the measurement results or Boolean. @retval {...} a dictionary data. @retval False means 'Unkown gyroscope range', that you need to check the "gyroscope range"...
[ "def", "getGyroData", "(", "self", ")", ":", "x", "=", "self", ".", "_readWord", "(", "self", ".", "REG_GYRO_XOUT_H", ")", "y", "=", "self", ".", "_readWord", "(", "self", ".", "REG_GYRO_YOUT_H", ")", "z", "=", "self", ".", "_readWord", "(", "self", ...
! Gets and returns the X, Y and Z values from the gyroscope @return a dictionary with the measurement results or Boolean. @retval {...} a dictionary data. @retval False means 'Unkown gyroscope range', that you need to check the "gyroscope range" configuration @note Resul...
[ "!", "Gets", "and", "returns", "the", "X", "Y", "and", "Z", "values", "from", "the", "gyroscope" ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Attitude/MPU6050.py#L498-L530
train
57,325
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Attitude/MPU6050.py
MPU6050.getAllData
def getAllData(self, temp = True, accel = True, gyro = True): """! Get all the available data. @param temp: True - Allow to return Temperature data @param accel: True - Allow to return Accelerometer data @param gyro: True - Allow to return Gyroscope data @return a dicti...
python
def getAllData(self, temp = True, accel = True, gyro = True): """! Get all the available data. @param temp: True - Allow to return Temperature data @param accel: True - Allow to return Accelerometer data @param gyro: True - Allow to return Gyroscope data @return a dicti...
[ "def", "getAllData", "(", "self", ",", "temp", "=", "True", ",", "accel", "=", "True", ",", "gyro", "=", "True", ")", ":", "allData", "=", "{", "}", "if", "temp", ":", "allData", "[", "\"temp\"", "]", "=", "self", ".", "getTemp", "(", ")", "if", ...
! Get all the available data. @param temp: True - Allow to return Temperature data @param accel: True - Allow to return Accelerometer data @param gyro: True - Allow to return Gyroscope data @return a dictionary data @retval {} Did not read any data @retv...
[ "!", "Get", "all", "the", "available", "data", "." ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Attitude/MPU6050.py#L533-L555
train
57,326
CodyKochmann/generators
generators/repeater.py
repeater
def repeater(pipe, how_many=2): ''' this function repeats each value in the pipeline however many times you need ''' r = range(how_many) for i in pipe: for _ in r: yield i
python
def repeater(pipe, how_many=2): ''' this function repeats each value in the pipeline however many times you need ''' r = range(how_many) for i in pipe: for _ in r: yield i
[ "def", "repeater", "(", "pipe", ",", "how_many", "=", "2", ")", ":", "r", "=", "range", "(", "how_many", ")", "for", "i", "in", "pipe", ":", "for", "_", "in", "r", ":", "yield", "i" ]
this function repeats each value in the pipeline however many times you need
[ "this", "function", "repeats", "each", "value", "in", "the", "pipeline", "however", "many", "times", "you", "need" ]
e4ca4dd25d5023a94b0349c69d6224070cc2526f
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/repeater.py#L7-L12
train
57,327
iron-lion/nJSD
src/njsd/entropy.py
kld
def kld(p1, p2): """Compute Kullback-Leibler divergence between p1 and p2. It assumes that p1 and p2 are already normalized that each of them sums to 1. """ return np.sum(np.where(p1 != 0, p1 * np.log(p1 / p2), 0))
python
def kld(p1, p2): """Compute Kullback-Leibler divergence between p1 and p2. It assumes that p1 and p2 are already normalized that each of them sums to 1. """ return np.sum(np.where(p1 != 0, p1 * np.log(p1 / p2), 0))
[ "def", "kld", "(", "p1", ",", "p2", ")", ":", "return", "np", ".", "sum", "(", "np", ".", "where", "(", "p1", "!=", "0", ",", "p1", "*", "np", ".", "log", "(", "p1", "/", "p2", ")", ",", "0", ")", ")" ]
Compute Kullback-Leibler divergence between p1 and p2. It assumes that p1 and p2 are already normalized that each of them sums to 1.
[ "Compute", "Kullback", "-", "Leibler", "divergence", "between", "p1", "and", "p2", ".", "It", "assumes", "that", "p1", "and", "p2", "are", "already", "normalized", "that", "each", "of", "them", "sums", "to", "1", "." ]
386397b7aa7251954771b2be4ce3a5d575033206
https://github.com/iron-lion/nJSD/blob/386397b7aa7251954771b2be4ce3a5d575033206/src/njsd/entropy.py#L42-L46
train
57,328
iron-lion/nJSD
src/njsd/entropy.py
jsd
def jsd(p1, p2): """Compute Jensen-Shannon divergence between p1 and p2. It assumes that p1 and p2 are already normalized that each of them sums to 1. """ m = (p1 + p2) / 2 return (kld(p1, m) + kld(p2, m)) / 2
python
def jsd(p1, p2): """Compute Jensen-Shannon divergence between p1 and p2. It assumes that p1 and p2 are already normalized that each of them sums to 1. """ m = (p1 + p2) / 2 return (kld(p1, m) + kld(p2, m)) / 2
[ "def", "jsd", "(", "p1", ",", "p2", ")", ":", "m", "=", "(", "p1", "+", "p2", ")", "/", "2", "return", "(", "kld", "(", "p1", ",", "m", ")", "+", "kld", "(", "p2", ",", "m", ")", ")", "/", "2" ]
Compute Jensen-Shannon divergence between p1 and p2. It assumes that p1 and p2 are already normalized that each of them sums to 1.
[ "Compute", "Jensen", "-", "Shannon", "divergence", "between", "p1", "and", "p2", ".", "It", "assumes", "that", "p1", "and", "p2", "are", "already", "normalized", "that", "each", "of", "them", "sums", "to", "1", "." ]
386397b7aa7251954771b2be4ce3a5d575033206
https://github.com/iron-lion/nJSD/blob/386397b7aa7251954771b2be4ce3a5d575033206/src/njsd/entropy.py#L49-L54
train
57,329
iron-lion/nJSD
src/njsd/entropy.py
njsd
def njsd(network, ref_gene_expression_dict, query_gene_expression_dict, gene_set): """Calculate Jensen-Shannon divergence between query and reference gene expression profile. """ gene_jsd_dict = dict() reference_genes = ref_gene_expression_dict.keys() assert len(reference_genes) != 'Reference g...
python
def njsd(network, ref_gene_expression_dict, query_gene_expression_dict, gene_set): """Calculate Jensen-Shannon divergence between query and reference gene expression profile. """ gene_jsd_dict = dict() reference_genes = ref_gene_expression_dict.keys() assert len(reference_genes) != 'Reference g...
[ "def", "njsd", "(", "network", ",", "ref_gene_expression_dict", ",", "query_gene_expression_dict", ",", "gene_set", ")", ":", "gene_jsd_dict", "=", "dict", "(", ")", "reference_genes", "=", "ref_gene_expression_dict", ".", "keys", "(", ")", "assert", "len", "(", ...
Calculate Jensen-Shannon divergence between query and reference gene expression profile.
[ "Calculate", "Jensen", "-", "Shannon", "divergence", "between", "query", "and", "reference", "gene", "expression", "profile", "." ]
386397b7aa7251954771b2be4ce3a5d575033206
https://github.com/iron-lion/nJSD/blob/386397b7aa7251954771b2be4ce3a5d575033206/src/njsd/entropy.py#L57-L83
train
57,330
nuSTORM/gnomon
gnomon/processors/__init__.py
lookupProcessor
def lookupProcessor(name): """Lookup processor class object by its name""" if name in _proc_lookup: return _proc_lookup[name] else: error_string = 'If you are creating a new processor, please read the\ documentation on creating a new processor' raise LookupError("Unknown processor %s...
python
def lookupProcessor(name): """Lookup processor class object by its name""" if name in _proc_lookup: return _proc_lookup[name] else: error_string = 'If you are creating a new processor, please read the\ documentation on creating a new processor' raise LookupError("Unknown processor %s...
[ "def", "lookupProcessor", "(", "name", ")", ":", "if", "name", "in", "_proc_lookup", ":", "return", "_proc_lookup", "[", "name", "]", "else", ":", "error_string", "=", "'If you are creating a new processor, please read the\\\ndocumentation on creating a new processor'", "ra...
Lookup processor class object by its name
[ "Lookup", "processor", "class", "object", "by", "its", "name" ]
7616486ecd6e26b76f677c380e62db1c0ade558a
https://github.com/nuSTORM/gnomon/blob/7616486ecd6e26b76f677c380e62db1c0ade558a/gnomon/processors/__init__.py#L39-L46
train
57,331
wuher/devil
devil/fields/__init__.py
serialize
def serialize(self, value, entity=None, request=None): """ Validate and serialize the value. This is the default implementation """ ret = self.from_python(value) self.validate(ret) self.run_validators(value) return ret
python
def serialize(self, value, entity=None, request=None): """ Validate and serialize the value. This is the default implementation """ ret = self.from_python(value) self.validate(ret) self.run_validators(value) return ret
[ "def", "serialize", "(", "self", ",", "value", ",", "entity", "=", "None", ",", "request", "=", "None", ")", ":", "ret", "=", "self", ".", "from_python", "(", "value", ")", "self", ".", "validate", "(", "ret", ")", "self", ".", "run_validators", "(",...
Validate and serialize the value. This is the default implementation
[ "Validate", "and", "serialize", "the", "value", "." ]
a8834d4f88d915a21754c6b96f99d0ad9123ad4d
https://github.com/wuher/devil/blob/a8834d4f88d915a21754c6b96f99d0ad9123ad4d/devil/fields/__init__.py#L23-L32
train
57,332
CodyKochmann/generators
generators/side_task.py
side_task
def side_task(pipe, *side_jobs): ''' allows you to run a function in a pipeline without affecting the data ''' # validate the input assert iterable(pipe), 'side_task needs the first argument to be iterable' for sj in side_jobs: assert callable(sj), 'all side_jobs need to be functions, not {}'.fo...
python
def side_task(pipe, *side_jobs): ''' allows you to run a function in a pipeline without affecting the data ''' # validate the input assert iterable(pipe), 'side_task needs the first argument to be iterable' for sj in side_jobs: assert callable(sj), 'all side_jobs need to be functions, not {}'.fo...
[ "def", "side_task", "(", "pipe", ",", "*", "side_jobs", ")", ":", "# validate the input", "assert", "iterable", "(", "pipe", ")", ",", "'side_task needs the first argument to be iterable'", "for", "sj", "in", "side_jobs", ":", "assert", "callable", "(", "sj", ")",...
allows you to run a function in a pipeline without affecting the data
[ "allows", "you", "to", "run", "a", "function", "in", "a", "pipeline", "without", "affecting", "the", "data" ]
e4ca4dd25d5023a94b0349c69d6224070cc2526f
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/side_task.py#L24-L34
train
57,333
TissueMAPS/TmDeploy
elasticluster/elasticluster/providers/ec2_boto.py
BotoCloudProvider._connect
def _connect(self): """Connects to the ec2 cloud provider :return: :py:class:`boto.ec2.connection.EC2Connection` :raises: Generic exception on error """ # check for existing connection if self._ec2_connection: return self._ec2_connection if not self....
python
def _connect(self): """Connects to the ec2 cloud provider :return: :py:class:`boto.ec2.connection.EC2Connection` :raises: Generic exception on error """ # check for existing connection if self._ec2_connection: return self._ec2_connection if not self....
[ "def", "_connect", "(", "self", ")", ":", "# check for existing connection", "if", "self", ".", "_ec2_connection", ":", "return", "self", ".", "_ec2_connection", "if", "not", "self", ".", "_vpc", ":", "vpc_connection", "=", "None", "try", ":", "log", ".", "d...
Connects to the ec2 cloud provider :return: :py:class:`boto.ec2.connection.EC2Connection` :raises: Generic exception on error
[ "Connects", "to", "the", "ec2", "cloud", "provider" ]
f891b4ffb21431988bc4a063ae871da3bf284a45
https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/providers/ec2_boto.py#L107-L167
train
57,334
CodyKochmann/generators
generators/split.py
split
def split(pipe, splitter, skip_empty=False): ''' this function works a lot like groupby but splits on given patterns, the same behavior as str.split provides. if skip_empty is True, split only yields pieces that have contents Example: splitting 1011101010101 by ...
python
def split(pipe, splitter, skip_empty=False): ''' this function works a lot like groupby but splits on given patterns, the same behavior as str.split provides. if skip_empty is True, split only yields pieces that have contents Example: splitting 1011101010101 by ...
[ "def", "split", "(", "pipe", ",", "splitter", ",", "skip_empty", "=", "False", ")", ":", "splitter", "=", "tuple", "(", "splitter", ")", "len_splitter", "=", "len", "(", "splitter", ")", "pipe", "=", "iter", "(", "pipe", ")", "current", "=", "deque", ...
this function works a lot like groupby but splits on given patterns, the same behavior as str.split provides. if skip_empty is True, split only yields pieces that have contents Example: splitting 1011101010101 by 10 returns ,11,,,,1 Or if s...
[ "this", "function", "works", "a", "lot", "like", "groupby", "but", "splits", "on", "given", "patterns", "the", "same", "behavior", "as", "str", ".", "split", "provides", ".", "if", "skip_empty", "is", "True", "split", "only", "yields", "pieces", "that", "h...
e4ca4dd25d5023a94b0349c69d6224070cc2526f
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/split.py#L12-L46
train
57,335
erickgnavar/serpost
serpost/serpost.py
query_tracking_code
def query_tracking_code(tracking_code, year=None): """ Given a tracking_code return a list of events related the tracking code """ payload = { 'Anio': year or datetime.now().year, 'Tracking': tracking_code, } response = _make_request(TRACKING_URL, payload) if not response['d...
python
def query_tracking_code(tracking_code, year=None): """ Given a tracking_code return a list of events related the tracking code """ payload = { 'Anio': year or datetime.now().year, 'Tracking': tracking_code, } response = _make_request(TRACKING_URL, payload) if not response['d...
[ "def", "query_tracking_code", "(", "tracking_code", ",", "year", "=", "None", ")", ":", "payload", "=", "{", "'Anio'", ":", "year", "or", "datetime", ".", "now", "(", ")", ".", "year", ",", "'Tracking'", ":", "tracking_code", ",", "}", "response", "=", ...
Given a tracking_code return a list of events related the tracking code
[ "Given", "a", "tracking_code", "return", "a", "list", "of", "events", "related", "the", "tracking", "code" ]
1cf2ddd4e2fc2549ea6ebe426a14ec423f9ab0fa
https://github.com/erickgnavar/serpost/blob/1cf2ddd4e2fc2549ea6ebe426a14ec423f9ab0fa/serpost/serpost.py#L40-L61
train
57,336
inveniosoftware-attic/invenio-comments
invenio_comments/utils.py
comments_nb_counts
def comments_nb_counts(): """Get number of comments for the record `recid`.""" recid = request.view_args.get('recid') if recid is None: return elif recid == 0: return 0 else: return CmtRECORDCOMMENT.count(*[ CmtRECORDCOMMENT.id_bibrec == recid, CmtREC...
python
def comments_nb_counts(): """Get number of comments for the record `recid`.""" recid = request.view_args.get('recid') if recid is None: return elif recid == 0: return 0 else: return CmtRECORDCOMMENT.count(*[ CmtRECORDCOMMENT.id_bibrec == recid, CmtREC...
[ "def", "comments_nb_counts", "(", ")", ":", "recid", "=", "request", ".", "view_args", ".", "get", "(", "'recid'", ")", "if", "recid", "is", "None", ":", "return", "elif", "recid", "==", "0", ":", "return", "0", "else", ":", "return", "CmtRECORDCOMMENT",...
Get number of comments for the record `recid`.
[ "Get", "number", "of", "comments", "for", "the", "record", "recid", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/utils.py#L27-L40
train
57,337
adamfast/faadata
faadata/airports/utils.py
decide_k
def decide_k(airport_code): """A function to decide if a leading 'K' is throwing off an airport match and return the correct code.""" if airport_code[:1].upper() == 'K': try: # if there's a match without the K that's likely what it is. return Airport.objects.get(location_identifier__iexact=...
python
def decide_k(airport_code): """A function to decide if a leading 'K' is throwing off an airport match and return the correct code.""" if airport_code[:1].upper() == 'K': try: # if there's a match without the K that's likely what it is. return Airport.objects.get(location_identifier__iexact=...
[ "def", "decide_k", "(", "airport_code", ")", ":", "if", "airport_code", "[", ":", "1", "]", ".", "upper", "(", ")", "==", "'K'", ":", "try", ":", "# if there's a match without the K that's likely what it is.", "return", "Airport", ".", "objects", ".", "get", "...
A function to decide if a leading 'K' is throwing off an airport match and return the correct code.
[ "A", "function", "to", "decide", "if", "a", "leading", "K", "is", "throwing", "off", "an", "airport", "match", "and", "return", "the", "correct", "code", "." ]
3c7d651b28160b7cb24724f67ebffd6bd0b490b9
https://github.com/adamfast/faadata/blob/3c7d651b28160b7cb24724f67ebffd6bd0b490b9/faadata/airports/utils.py#L3-L12
train
57,338
slickqa/python-client
slickqa/micromodels/packages/PySO8601/datetimestamps.py
parse_date
def parse_date(datestring): """Attepmts to parse an ISO8601 formatted ``datestring``. Returns a ``datetime.datetime`` object. """ datestring = str(datestring).strip() if not datestring[0].isdigit(): raise ParseError() if 'W' in datestring.upper(): try: datestring =...
python
def parse_date(datestring): """Attepmts to parse an ISO8601 formatted ``datestring``. Returns a ``datetime.datetime`` object. """ datestring = str(datestring).strip() if not datestring[0].isdigit(): raise ParseError() if 'W' in datestring.upper(): try: datestring =...
[ "def", "parse_date", "(", "datestring", ")", ":", "datestring", "=", "str", "(", "datestring", ")", ".", "strip", "(", ")", "if", "not", "datestring", "[", "0", "]", ".", "isdigit", "(", ")", ":", "raise", "ParseError", "(", ")", "if", "'W'", "in", ...
Attepmts to parse an ISO8601 formatted ``datestring``. Returns a ``datetime.datetime`` object.
[ "Attepmts", "to", "parse", "an", "ISO8601", "formatted", "datestring", "." ]
1d36b4977cd4140d7d24917cab2b3f82b60739c2
https://github.com/slickqa/python-client/blob/1d36b4977cd4140d7d24917cab2b3f82b60739c2/slickqa/micromodels/packages/PySO8601/datetimestamps.py#L91-L120
train
57,339
slickqa/python-client
slickqa/micromodels/packages/PySO8601/datetimestamps.py
parse_time
def parse_time(timestring): """Attepmts to parse an ISO8601 formatted ``timestring``. Returns a ``datetime.datetime`` object. """ timestring = str(timestring).strip() for regex, pattern in TIME_FORMATS: if regex.match(timestring): found = regex.search(timestring).groupdict() ...
python
def parse_time(timestring): """Attepmts to parse an ISO8601 formatted ``timestring``. Returns a ``datetime.datetime`` object. """ timestring = str(timestring).strip() for regex, pattern in TIME_FORMATS: if regex.match(timestring): found = regex.search(timestring).groupdict() ...
[ "def", "parse_time", "(", "timestring", ")", ":", "timestring", "=", "str", "(", "timestring", ")", ".", "strip", "(", ")", "for", "regex", ",", "pattern", "in", "TIME_FORMATS", ":", "if", "regex", ".", "match", "(", "timestring", ")", ":", "found", "=...
Attepmts to parse an ISO8601 formatted ``timestring``. Returns a ``datetime.datetime`` object.
[ "Attepmts", "to", "parse", "an", "ISO8601", "formatted", "timestring", "." ]
1d36b4977cd4140d7d24917cab2b3f82b60739c2
https://github.com/slickqa/python-client/blob/1d36b4977cd4140d7d24917cab2b3f82b60739c2/slickqa/micromodels/packages/PySO8601/datetimestamps.py#L123-L145
train
57,340
thespacedoctor/fundamentals
fundamentals/mysql/database.py
database.connect
def connect(self): """connect to the database **Return:** - ``dbConn`` -- the database connection See the class docstring for usage """ self.log.debug('starting the ``get`` method') dbSettings = self.dbSettings port = False if "tunnel" in d...
python
def connect(self): """connect to the database **Return:** - ``dbConn`` -- the database connection See the class docstring for usage """ self.log.debug('starting the ``get`` method') dbSettings = self.dbSettings port = False if "tunnel" in d...
[ "def", "connect", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "'starting the ``get`` method'", ")", "dbSettings", "=", "self", ".", "dbSettings", "port", "=", "False", "if", "\"tunnel\"", "in", "dbSettings", "and", "dbSettings", "[", "\"tun...
connect to the database **Return:** - ``dbConn`` -- the database connection See the class docstring for usage
[ "connect", "to", "the", "database" ]
1d2c007ac74442ec2eabde771cfcacdb9c1ab382
https://github.com/thespacedoctor/fundamentals/blob/1d2c007ac74442ec2eabde771cfcacdb9c1ab382/fundamentals/mysql/database.py#L85-L125
train
57,341
lycantropos/paradigm
paradigm/cached.py
map_
def map_(cache: Mapping[Domain, Range]) -> Operator[Map[Domain, Range]]: """ Returns decorator that calls wrapped function if nothing was found in cache for its argument. Wrapped function arguments should be hashable. """ def wrapper(function: Map[Domain, Range]) -> Map[Domain, Range]: ...
python
def map_(cache: Mapping[Domain, Range]) -> Operator[Map[Domain, Range]]: """ Returns decorator that calls wrapped function if nothing was found in cache for its argument. Wrapped function arguments should be hashable. """ def wrapper(function: Map[Domain, Range]) -> Map[Domain, Range]: ...
[ "def", "map_", "(", "cache", ":", "Mapping", "[", "Domain", ",", "Range", "]", ")", "->", "Operator", "[", "Map", "[", "Domain", ",", "Range", "]", "]", ":", "def", "wrapper", "(", "function", ":", "Map", "[", "Domain", ",", "Range", "]", ")", "-...
Returns decorator that calls wrapped function if nothing was found in cache for its argument. Wrapped function arguments should be hashable.
[ "Returns", "decorator", "that", "calls", "wrapped", "function", "if", "nothing", "was", "found", "in", "cache", "for", "its", "argument", "." ]
70415f77964dbb1b6d444f890a5d988174194ff0
https://github.com/lycantropos/paradigm/blob/70415f77964dbb1b6d444f890a5d988174194ff0/paradigm/cached.py#L15-L33
train
57,342
lycantropos/paradigm
paradigm/cached.py
updatable_map
def updatable_map(cache: MutableMapping[Domain, Range]) -> Operator[Map]: """ Returns decorator that calls wrapped function if nothing was found in cache for its argument and reuses result afterwards. Wrapped function arguments should be hashable. """ def wrapper(function: Map[Domain, Rang...
python
def updatable_map(cache: MutableMapping[Domain, Range]) -> Operator[Map]: """ Returns decorator that calls wrapped function if nothing was found in cache for its argument and reuses result afterwards. Wrapped function arguments should be hashable. """ def wrapper(function: Map[Domain, Rang...
[ "def", "updatable_map", "(", "cache", ":", "MutableMapping", "[", "Domain", ",", "Range", "]", ")", "->", "Operator", "[", "Map", "]", ":", "def", "wrapper", "(", "function", ":", "Map", "[", "Domain", ",", "Range", "]", ")", "->", "Map", "[", "Domai...
Returns decorator that calls wrapped function if nothing was found in cache for its argument and reuses result afterwards. Wrapped function arguments should be hashable.
[ "Returns", "decorator", "that", "calls", "wrapped", "function", "if", "nothing", "was", "found", "in", "cache", "for", "its", "argument", "and", "reuses", "result", "afterwards", "." ]
70415f77964dbb1b6d444f890a5d988174194ff0
https://github.com/lycantropos/paradigm/blob/70415f77964dbb1b6d444f890a5d988174194ff0/paradigm/cached.py#L37-L58
train
57,343
lycantropos/paradigm
paradigm/cached.py
property_
def property_(getter: Map[Domain, Range]) -> property: """ Returns property that calls given getter on the first access and reuses result afterwards. Class instances should be hashable and weak referenceable. """ return property(map_(WeakKeyDictionary())(getter))
python
def property_(getter: Map[Domain, Range]) -> property: """ Returns property that calls given getter on the first access and reuses result afterwards. Class instances should be hashable and weak referenceable. """ return property(map_(WeakKeyDictionary())(getter))
[ "def", "property_", "(", "getter", ":", "Map", "[", "Domain", ",", "Range", "]", ")", "->", "property", ":", "return", "property", "(", "map_", "(", "WeakKeyDictionary", "(", ")", ")", "(", "getter", ")", ")" ]
Returns property that calls given getter on the first access and reuses result afterwards. Class instances should be hashable and weak referenceable.
[ "Returns", "property", "that", "calls", "given", "getter", "on", "the", "first", "access", "and", "reuses", "result", "afterwards", "." ]
70415f77964dbb1b6d444f890a5d988174194ff0
https://github.com/lycantropos/paradigm/blob/70415f77964dbb1b6d444f890a5d988174194ff0/paradigm/cached.py#L61-L68
train
57,344
clinicedc/edc-auth
edc_auth/views/login_view.py
LoginView.get_context_data
def get_context_data(self, **kwargs): """Tests cookies. """ self.request.session.set_test_cookie() if not self.request.session.test_cookie_worked(): messages.add_message( self.request, messages.ERROR, "Please enable cookies.") self.request.session.dele...
python
def get_context_data(self, **kwargs): """Tests cookies. """ self.request.session.set_test_cookie() if not self.request.session.test_cookie_worked(): messages.add_message( self.request, messages.ERROR, "Please enable cookies.") self.request.session.dele...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "request", ".", "session", ".", "set_test_cookie", "(", ")", "if", "not", "self", ".", "request", ".", "session", ".", "test_cookie_worked", "(", ")", ":", "messages"...
Tests cookies.
[ "Tests", "cookies", "." ]
e633a5461139d3799f389f7bed0e02c9d2c1e103
https://github.com/clinicedc/edc-auth/blob/e633a5461139d3799f389f7bed0e02c9d2c1e103/edc_auth/views/login_view.py#L13-L21
train
57,345
PatrikValkovic/grammpy
grammpy/transforms/Traversing.py
Traversing.print
def print(root): # type: (Union[Nonterminal,Terminal,Rule])-> str """ Transform the parsed tree to the string. Expects tree like structure. You can see example output below. (R)SplitRules26 |--(N)Iterate | `--(R)SplitRules30 | `--(N)Symb | ...
python
def print(root): # type: (Union[Nonterminal,Terminal,Rule])-> str """ Transform the parsed tree to the string. Expects tree like structure. You can see example output below. (R)SplitRules26 |--(N)Iterate | `--(R)SplitRules30 | `--(N)Symb | ...
[ "def", "print", "(", "root", ")", ":", "# type: (Union[Nonterminal,Terminal,Rule])-> str", "# print the part before the element", "def", "print_before", "(", "previous", "=", "0", ",", "defined", "=", "None", ",", "is_last", "=", "False", ")", ":", "defined", "=", ...
Transform the parsed tree to the string. Expects tree like structure. You can see example output below. (R)SplitRules26 |--(N)Iterate | `--(R)SplitRules30 | `--(N)Symb | `--(R)SplitRules4 | `--(T)e `--(N)Concat `--(R)Split...
[ "Transform", "the", "parsed", "tree", "to", "the", "string", ".", "Expects", "tree", "like", "structure", ".", "You", "can", "see", "example", "output", "below", "." ]
879ce0ef794ac2823acc19314fcd7a8aba53e50f
https://github.com/PatrikValkovic/grammpy/blob/879ce0ef794ac2823acc19314fcd7a8aba53e50f/grammpy/transforms/Traversing.py#L143-L209
train
57,346
freevoid/django-datafilters
datafilters/views.py
FilterFormMixin.get_filter
def get_filter(self): """ Get FilterForm instance. """ return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining)
python
def get_filter(self): """ Get FilterForm instance. """ return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining)
[ "def", "get_filter", "(", "self", ")", ":", "return", "self", ".", "filter_form_cls", "(", "self", ".", "request", ".", "GET", ",", "runtime_context", "=", "self", ".", "get_runtime_context", "(", ")", ",", "use_filter_chaining", "=", "self", ".", "use_filte...
Get FilterForm instance.
[ "Get", "FilterForm", "instance", "." ]
99051b3b3e97946981c0e9697576b0100093287c
https://github.com/freevoid/django-datafilters/blob/99051b3b3e97946981c0e9697576b0100093287c/datafilters/views.py#L14-L20
train
57,347
freevoid/django-datafilters
datafilters/views.py
FilterFormMixin.get_context_data
def get_context_data(self, **kwargs): """ Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization. """ context ...
python
def get_context_data(self, **kwargs): """ Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization. """ context ...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "FilterFormMixin", ",", "self", ")", ".", "get_context_data", "(", "*", "*", "kwargs", ")", "context", "[", "self", ".", "context_filterform_name", "]"...
Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization.
[ "Add", "filter", "form", "to", "the", "context", "." ]
99051b3b3e97946981c0e9697576b0100093287c
https://github.com/freevoid/django-datafilters/blob/99051b3b3e97946981c0e9697576b0100093287c/datafilters/views.py#L33-L43
train
57,348
chaosim/dao
dao/compile.py
compile_to_python
def compile_to_python(exp, env, done=None): '''assemble steps from dao expression to python code''' original_exp = exp compiler = Compiler() if done is None: done = il.Done(compiler.new_var(il.ConstLocalVar('v'))) compiler.exit_block_cont_map = {} compiler.continue_block_cont_map = {} compile...
python
def compile_to_python(exp, env, done=None): '''assemble steps from dao expression to python code''' original_exp = exp compiler = Compiler() if done is None: done = il.Done(compiler.new_var(il.ConstLocalVar('v'))) compiler.exit_block_cont_map = {} compiler.continue_block_cont_map = {} compile...
[ "def", "compile_to_python", "(", "exp", ",", "env", ",", "done", "=", "None", ")", ":", "original_exp", "=", "exp", "compiler", "=", "Compiler", "(", ")", "if", "done", "is", "None", ":", "done", "=", "il", ".", "Done", "(", "compiler", ".", "new_var...
assemble steps from dao expression to python code
[ "assemble", "steps", "from", "dao", "expression", "to", "python", "code" ]
d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa
https://github.com/chaosim/dao/blob/d7ba65c98ee063aefd1ff4eabb192d1536fdbaaa/dao/compile.py#L41-L66
train
57,349
CodyKochmann/generators
generators/last.py
last
def last(pipe, items=1): ''' this function simply returns the last item in an iterable ''' if items == 1: tmp=None for i in pipe: tmp=i return tmp else: return tuple(deque(pipe, maxlen=items))
python
def last(pipe, items=1): ''' this function simply returns the last item in an iterable ''' if items == 1: tmp=None for i in pipe: tmp=i return tmp else: return tuple(deque(pipe, maxlen=items))
[ "def", "last", "(", "pipe", ",", "items", "=", "1", ")", ":", "if", "items", "==", "1", ":", "tmp", "=", "None", "for", "i", "in", "pipe", ":", "tmp", "=", "i", "return", "tmp", "else", ":", "return", "tuple", "(", "deque", "(", "pipe", ",", ...
this function simply returns the last item in an iterable
[ "this", "function", "simply", "returns", "the", "last", "item", "in", "an", "iterable" ]
e4ca4dd25d5023a94b0349c69d6224070cc2526f
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/last.py#L9-L17
train
57,350
kgaughan/dbkit
examples/counters.py
print_help
def print_help(filename, table, dest=sys.stdout): """ Print help to the given destination file object. """ cmds = '|'.join(sorted(table.keys())) print >> dest, "Syntax: %s %s [args]" % (path.basename(filename), cmds)
python
def print_help(filename, table, dest=sys.stdout): """ Print help to the given destination file object. """ cmds = '|'.join(sorted(table.keys())) print >> dest, "Syntax: %s %s [args]" % (path.basename(filename), cmds)
[ "def", "print_help", "(", "filename", ",", "table", ",", "dest", "=", "sys", ".", "stdout", ")", ":", "cmds", "=", "'|'", ".", "join", "(", "sorted", "(", "table", ".", "keys", "(", ")", ")", ")", "print", ">>", "dest", ",", "\"Syntax: %s %s [args]\"...
Print help to the given destination file object.
[ "Print", "help", "to", "the", "given", "destination", "file", "object", "." ]
2aef6376a60965d7820c91692046f4bcf7d43640
https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/examples/counters.py#L82-L87
train
57,351
kgaughan/dbkit
examples/counters.py
dispatch
def dispatch(table, args): """ Dispatches to a function based on the contents of `args`. """ # No arguments: print help. if len(args) == 1: print_help(args[0], table) sys.exit(0) # Bad command or incorrect number of arguments: print help to stderr. if args[1] not in table or...
python
def dispatch(table, args): """ Dispatches to a function based on the contents of `args`. """ # No arguments: print help. if len(args) == 1: print_help(args[0], table) sys.exit(0) # Bad command or incorrect number of arguments: print help to stderr. if args[1] not in table or...
[ "def", "dispatch", "(", "table", ",", "args", ")", ":", "# No arguments: print help.", "if", "len", "(", "args", ")", "==", "1", ":", "print_help", "(", "args", "[", "0", "]", ",", "table", ")", "sys", ".", "exit", "(", "0", ")", "# Bad command or inco...
Dispatches to a function based on the contents of `args`.
[ "Dispatches", "to", "a", "function", "based", "on", "the", "contents", "of", "args", "." ]
2aef6376a60965d7820c91692046f4bcf7d43640
https://github.com/kgaughan/dbkit/blob/2aef6376a60965d7820c91692046f4bcf7d43640/examples/counters.py#L90-L115
train
57,352
consbio/parserutils
parserutils/strings.py
find_all
def find_all(s, sub, start=0, end=0, limit=-1, reverse=False): """ Find all indexes of sub in s. :param s: the string to search :param sub: the string to search for :param start: the index in s at which to begin the search (same as in ''.find) :param end: the index in s at which to stop searchi...
python
def find_all(s, sub, start=0, end=0, limit=-1, reverse=False): """ Find all indexes of sub in s. :param s: the string to search :param sub: the string to search for :param start: the index in s at which to begin the search (same as in ''.find) :param end: the index in s at which to stop searchi...
[ "def", "find_all", "(", "s", ",", "sub", ",", "start", "=", "0", ",", "end", "=", "0", ",", "limit", "=", "-", "1", ",", "reverse", "=", "False", ")", ":", "indexes", "=", "[", "]", "if", "not", "bool", "(", "s", "and", "sub", ")", ":", "re...
Find all indexes of sub in s. :param s: the string to search :param sub: the string to search for :param start: the index in s at which to begin the search (same as in ''.find) :param end: the index in s at which to stop searching (same as in ''.find) :param limit: the maximum number of matches to ...
[ "Find", "all", "indexes", "of", "sub", "in", "s", "." ]
f13f80db99ed43479336b116e38512e3566e4623
https://github.com/consbio/parserutils/blob/f13f80db99ed43479336b116e38512e3566e4623/parserutils/strings.py#L72-L117
train
57,353
inveniosoftware-attic/invenio-utils
invenio_utils/container.py
get_substructure
def get_substructure(data, path): """ Tries to retrieve a sub-structure within some data. If the path does not match any sub-structure, returns None. >>> data = {'a': 5, 'b': {'c': [1, 2, [{'f': [57]}], 4], 'd': 'test'}} >>> get_substructure(island, "bc") [1, 2, [{'f': [57]}], 4] >>> get_su...
python
def get_substructure(data, path): """ Tries to retrieve a sub-structure within some data. If the path does not match any sub-structure, returns None. >>> data = {'a': 5, 'b': {'c': [1, 2, [{'f': [57]}], 4], 'd': 'test'}} >>> get_substructure(island, "bc") [1, 2, [{'f': [57]}], 4] >>> get_su...
[ "def", "get_substructure", "(", "data", ",", "path", ")", ":", "if", "not", "len", "(", "path", ")", ":", "return", "data", "try", ":", "return", "get_substructure", "(", "data", "[", "path", "[", "0", "]", "]", ",", "path", "[", "1", ":", "]", "...
Tries to retrieve a sub-structure within some data. If the path does not match any sub-structure, returns None. >>> data = {'a': 5, 'b': {'c': [1, 2, [{'f': [57]}], 4], 'd': 'test'}} >>> get_substructure(island, "bc") [1, 2, [{'f': [57]}], 4] >>> get_substructure(island, ['b', 'c']) [1, 2, [{'f...
[ "Tries", "to", "retrieve", "a", "sub", "-", "structure", "within", "some", "data", ".", "If", "the", "path", "does", "not", "match", "any", "sub", "-", "structure", "returns", "None", "." ]
9a1c6db4e3f1370901f329f510480dd8df188296
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/container.py#L23-L53
train
57,354
CodyKochmann/generators
generators/iterable.py
iterable
def iterable(target): ''' returns true if the given argument is iterable ''' if any(i in ('next', '__next__', '__iter__') for i in dir(target)): return True else: try: iter(target) return True except: return False
python
def iterable(target): ''' returns true if the given argument is iterable ''' if any(i in ('next', '__next__', '__iter__') for i in dir(target)): return True else: try: iter(target) return True except: return False
[ "def", "iterable", "(", "target", ")", ":", "if", "any", "(", "i", "in", "(", "'next'", ",", "'__next__'", ",", "'__iter__'", ")", "for", "i", "in", "dir", "(", "target", ")", ")", ":", "return", "True", "else", ":", "try", ":", "iter", "(", "tar...
returns true if the given argument is iterable
[ "returns", "true", "if", "the", "given", "argument", "is", "iterable" ]
e4ca4dd25d5023a94b0349c69d6224070cc2526f
https://github.com/CodyKochmann/generators/blob/e4ca4dd25d5023a94b0349c69d6224070cc2526f/generators/iterable.py#L11-L20
train
57,355
kellerza/pyqwikswitch
pyqwikswitch/threaded.py
QSUsb._thread_worker
def _thread_worker(self): """Process callbacks from the queue populated by &listen.""" while self._running: # Retrieve next cmd, or block packet = self._queue.get(True) if isinstance(packet, dict) and QS_CMD in packet: try: self._ca...
python
def _thread_worker(self): """Process callbacks from the queue populated by &listen.""" while self._running: # Retrieve next cmd, or block packet = self._queue.get(True) if isinstance(packet, dict) and QS_CMD in packet: try: self._ca...
[ "def", "_thread_worker", "(", "self", ")", ":", "while", "self", ".", "_running", ":", "# Retrieve next cmd, or block", "packet", "=", "self", ".", "_queue", ".", "get", "(", "True", ")", "if", "isinstance", "(", "packet", ",", "dict", ")", "and", "QS_CMD"...
Process callbacks from the queue populated by &listen.
[ "Process", "callbacks", "from", "the", "queue", "populated", "by", "&listen", "." ]
9d4f080048221eaee93e3eefcf641919ff1af586
https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/threaded.py#L42-L53
train
57,356
kellerza/pyqwikswitch
pyqwikswitch/threaded.py
QSUsb._thread_listen
def _thread_listen(self): """The main &listen loop.""" while self._running: try: rest = requests.get(URL_LISTEN.format(self._url), timeout=self._timeout) if rest.status_code == 200: self._queue.put(rest.j...
python
def _thread_listen(self): """The main &listen loop.""" while self._running: try: rest = requests.get(URL_LISTEN.format(self._url), timeout=self._timeout) if rest.status_code == 200: self._queue.put(rest.j...
[ "def", "_thread_listen", "(", "self", ")", ":", "while", "self", ".", "_running", ":", "try", ":", "rest", "=", "requests", ".", "get", "(", "URL_LISTEN", ".", "format", "(", "self", ".", "_url", ")", ",", "timeout", "=", "self", ".", "_timeout", ")"...
The main &listen loop.
[ "The", "main", "&listen", "loop", "." ]
9d4f080048221eaee93e3eefcf641919ff1af586
https://github.com/kellerza/pyqwikswitch/blob/9d4f080048221eaee93e3eefcf641919ff1af586/pyqwikswitch/threaded.py#L55-L78
train
57,357
XRDX/pyleap
pyleap/color.py
hsla_to_rgba
def hsla_to_rgba(h, s, l, a): """ 0 <= H < 360, 0 <= s,l,a < 1 """ h = h % 360 s = max(0, min(1, s)) l = max(0, min(1, l)) a = max(0, min(1, a)) c = (1 - abs(2*l - 1)) * s x = c * (1 - abs(h/60%2 - 1)) m = l - c/2 if h<60: r, g, b = c, x, 0 elif h<120: r, g,...
python
def hsla_to_rgba(h, s, l, a): """ 0 <= H < 360, 0 <= s,l,a < 1 """ h = h % 360 s = max(0, min(1, s)) l = max(0, min(1, l)) a = max(0, min(1, a)) c = (1 - abs(2*l - 1)) * s x = c * (1 - abs(h/60%2 - 1)) m = l - c/2 if h<60: r, g, b = c, x, 0 elif h<120: r, g,...
[ "def", "hsla_to_rgba", "(", "h", ",", "s", ",", "l", ",", "a", ")", ":", "h", "=", "h", "%", "360", "s", "=", "max", "(", "0", ",", "min", "(", "1", ",", "s", ")", ")", "l", "=", "max", "(", "0", ",", "min", "(", "1", ",", "l", ")", ...
0 <= H < 360, 0 <= s,l,a < 1
[ "0", "<", "=", "H", "<", "360", "0", "<", "=", "s", "l", "a", "<", "1" ]
234c722cfbe66814254ab0d8f67d16b0b774f4d5
https://github.com/XRDX/pyleap/blob/234c722cfbe66814254ab0d8f67d16b0b774f4d5/pyleap/color.py#L40-L66
train
57,358
NickMonzillo/SmartCloud
SmartCloud/utils.py
dir_list
def dir_list(directory): '''Returns the list of all files in the directory.''' try: content = listdir(directory) return content except WindowsError as winErr: print("Directory error: " + str((winErr)))
python
def dir_list(directory): '''Returns the list of all files in the directory.''' try: content = listdir(directory) return content except WindowsError as winErr: print("Directory error: " + str((winErr)))
[ "def", "dir_list", "(", "directory", ")", ":", "try", ":", "content", "=", "listdir", "(", "directory", ")", "return", "content", "except", "WindowsError", "as", "winErr", ":", "print", "(", "\"Directory error: \"", "+", "str", "(", "(", "winErr", ")", ")"...
Returns the list of all files in the directory.
[ "Returns", "the", "list", "of", "all", "files", "in", "the", "directory", "." ]
481d1ef428427b452a8a787999c1d4a8868a3824
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L21-L27
train
57,359
NickMonzillo/SmartCloud
SmartCloud/utils.py
read_dir
def read_dir(directory): '''Returns the text of all files in a directory.''' content = dir_list(directory) text = '' for filename in content: text += read_file(directory + '/' + filename) text += ' ' return text
python
def read_dir(directory): '''Returns the text of all files in a directory.''' content = dir_list(directory) text = '' for filename in content: text += read_file(directory + '/' + filename) text += ' ' return text
[ "def", "read_dir", "(", "directory", ")", ":", "content", "=", "dir_list", "(", "directory", ")", "text", "=", "''", "for", "filename", "in", "content", ":", "text", "+=", "read_file", "(", "directory", "+", "'/'", "+", "filename", ")", "text", "+=", "...
Returns the text of all files in a directory.
[ "Returns", "the", "text", "of", "all", "files", "in", "a", "directory", "." ]
481d1ef428427b452a8a787999c1d4a8868a3824
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L29-L36
train
57,360
NickMonzillo/SmartCloud
SmartCloud/utils.py
colorize
def colorize(occurence,maxoccurence,minoccurence): '''A formula for determining colors.''' if occurence == maxoccurence: color = (255,0,0) elif occurence == minoccurence: color = (0,0,255) else: color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence...
python
def colorize(occurence,maxoccurence,minoccurence): '''A formula for determining colors.''' if occurence == maxoccurence: color = (255,0,0) elif occurence == minoccurence: color = (0,0,255) else: color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence...
[ "def", "colorize", "(", "occurence", ",", "maxoccurence", ",", "minoccurence", ")", ":", "if", "occurence", "==", "maxoccurence", ":", "color", "=", "(", "255", ",", "0", ",", "0", ")", "elif", "occurence", "==", "minoccurence", ":", "color", "=", "(", ...
A formula for determining colors.
[ "A", "formula", "for", "determining", "colors", "." ]
481d1ef428427b452a8a787999c1d4a8868a3824
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L50-L58
train
57,361
NickMonzillo/SmartCloud
SmartCloud/utils.py
fontsize
def fontsize(count,maxsize,minsize,maxcount): '''A formula for determining font sizes.''' size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount))) if size < minsize: size = minsize return size
python
def fontsize(count,maxsize,minsize,maxcount): '''A formula for determining font sizes.''' size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount))) if size < minsize: size = minsize return size
[ "def", "fontsize", "(", "count", ",", "maxsize", ",", "minsize", ",", "maxcount", ")", ":", "size", "=", "int", "(", "maxsize", "-", "(", "maxsize", ")", "*", "(", "(", "float", "(", "maxcount", "-", "count", ")", "/", "maxcount", ")", ")", ")", ...
A formula for determining font sizes.
[ "A", "formula", "for", "determining", "font", "sizes", "." ]
481d1ef428427b452a8a787999c1d4a8868a3824
https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L77-L82
train
57,362
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Display/SSD1306.py
SSD1306Base._init_display
def _init_display(self): """! \~english Initialize the SSD1306 display chip \~chinese 初始化SSD1306显示芯片 """ self._command([ # 0xAE self.CMD_SSD1306_DISPLAY_OFF, #Stop Scroll self.CMD_SSD1306_SET_SCROLL_DEACTIVE, ...
python
def _init_display(self): """! \~english Initialize the SSD1306 display chip \~chinese 初始化SSD1306显示芯片 """ self._command([ # 0xAE self.CMD_SSD1306_DISPLAY_OFF, #Stop Scroll self.CMD_SSD1306_SET_SCROLL_DEACTIVE, ...
[ "def", "_init_display", "(", "self", ")", ":", "self", ".", "_command", "(", "[", "# 0xAE", "self", ".", "CMD_SSD1306_DISPLAY_OFF", ",", "#Stop Scroll", "self", ".", "CMD_SSD1306_SET_SCROLL_DEACTIVE", ",", "# 0xA8 SET MULTIPLEX 0x3F", "self", ".", "CMD_SSD1306_SET_MUL...
! \~english Initialize the SSD1306 display chip \~chinese 初始化SSD1306显示芯片
[ "!", "\\", "~english", "Initialize", "the", "SSD1306", "display", "chip" ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Display/SSD1306.py#L161-L212
train
57,363
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Display/SSD1306.py
SSD1306Base.display
def display(self, buffer = None): """! \~english Write buffer to physical display. @param buffer: Data to display,If <b>None</b> mean will use self._buffer data to display \~chinese 将缓冲区写入物理显示屏。 @param buffer: 要显示的数据,如果是 <b>None</b>(默认) 将把 self._buffer 数据写入物理显示屏...
python
def display(self, buffer = None): """! \~english Write buffer to physical display. @param buffer: Data to display,If <b>None</b> mean will use self._buffer data to display \~chinese 将缓冲区写入物理显示屏。 @param buffer: 要显示的数据,如果是 <b>None</b>(默认) 将把 self._buffer 数据写入物理显示屏...
[ "def", "display", "(", "self", ",", "buffer", "=", "None", ")", ":", "if", "buffer", "!=", "None", ":", "self", ".", "_display_buffer", "(", "buffer", ")", "else", ":", "self", ".", "_display_buffer", "(", "self", ".", "_buffer", ")" ]
! \~english Write buffer to physical display. @param buffer: Data to display,If <b>None</b> mean will use self._buffer data to display \~chinese 将缓冲区写入物理显示屏。 @param buffer: 要显示的数据,如果是 <b>None</b>(默认) 将把 self._buffer 数据写入物理显示屏
[ "!", "\\", "~english", "Write", "buffer", "to", "physical", "display", "." ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Display/SSD1306.py#L290-L302
train
57,364
mobinrg/rpi_spark_drives
JMRPiSpark/Drives/Display/SSD1306.py
SSD1306Base.scrollWith
def scrollWith(self, hStart = 0x00, hEnd=0x00, vOffset = 0x00, vStart=0x00, vEnd=0x00, int = 0x00, dire = "left" ): """! \~english Scroll screen @param hStart: Set horizontal scroll PAGE start address, value can be chosen between 0 and 7 @param hEnd: Set horizontal scroll PAGE ...
python
def scrollWith(self, hStart = 0x00, hEnd=0x00, vOffset = 0x00, vStart=0x00, vEnd=0x00, int = 0x00, dire = "left" ): """! \~english Scroll screen @param hStart: Set horizontal scroll PAGE start address, value can be chosen between 0 and 7 @param hEnd: Set horizontal scroll PAGE ...
[ "def", "scrollWith", "(", "self", ",", "hStart", "=", "0x00", ",", "hEnd", "=", "0x00", ",", "vOffset", "=", "0x00", ",", "vStart", "=", "0x00", ",", "vEnd", "=", "0x00", ",", "int", "=", "0x00", ",", "dire", "=", "\"left\"", ")", ":", "self", "....
! \~english Scroll screen @param hStart: Set horizontal scroll PAGE start address, value can be chosen between 0 and 7 @param hEnd: Set horizontal scroll PAGE end address, value can be chose between 0 and 7 @param vOffset: Vertical scroll offset row, if set to 0x00(0) means off...
[ "!", "\\", "~english", "Scroll", "screen" ]
e1602d8268a5ef48e9e0a8b37de89e0233f946ea
https://github.com/mobinrg/rpi_spark_drives/blob/e1602d8268a5ef48e9e0a8b37de89e0233f946ea/JMRPiSpark/Drives/Display/SSD1306.py#L365-L405
train
57,365
praekeltfoundation/seed-scheduler
scheduler/tasks.py
QueueTasks.run
def run(self, schedule_type, lookup_id, **kwargs): """ Loads Schedule linked to provided lookup """ log = self.get_logger(**kwargs) log.info("Queuing <%s> <%s>" % (schedule_type, lookup_id)) task_run = QueueTaskRun() task_run.task_id = self.request.id or uuid4() ...
python
def run(self, schedule_type, lookup_id, **kwargs): """ Loads Schedule linked to provided lookup """ log = self.get_logger(**kwargs) log.info("Queuing <%s> <%s>" % (schedule_type, lookup_id)) task_run = QueueTaskRun() task_run.task_id = self.request.id or uuid4() ...
[ "def", "run", "(", "self", ",", "schedule_type", ",", "lookup_id", ",", "*", "*", "kwargs", ")", ":", "log", "=", "self", ".", "get_logger", "(", "*", "*", "kwargs", ")", "log", ".", "info", "(", "\"Queuing <%s> <%s>\"", "%", "(", "schedule_type", ",",...
Loads Schedule linked to provided lookup
[ "Loads", "Schedule", "linked", "to", "provided", "lookup" ]
cec47fe2319c28cbb1c6dcc1131fe30c835270e2
https://github.com/praekeltfoundation/seed-scheduler/blob/cec47fe2319c28cbb1c6dcc1131fe30c835270e2/scheduler/tasks.py#L128-L188
train
57,366
Julian/Minion
minion/renderers.py
bind
def bind(renderer, to): """ Bind a renderer to the given callable by constructing a new rendering view. """ @wraps(to) def view(request, **kwargs): try: returned = to(request, **kwargs) except Exception as error: view_error = getattr(renderer, "view_error", ...
python
def bind(renderer, to): """ Bind a renderer to the given callable by constructing a new rendering view. """ @wraps(to) def view(request, **kwargs): try: returned = to(request, **kwargs) except Exception as error: view_error = getattr(renderer, "view_error", ...
[ "def", "bind", "(", "renderer", ",", "to", ")", ":", "@", "wraps", "(", "to", ")", "def", "view", "(", "request", ",", "*", "*", "kwargs", ")", ":", "try", ":", "returned", "=", "to", "(", "request", ",", "*", "*", "kwargs", ")", "except", "Exc...
Bind a renderer to the given callable by constructing a new rendering view.
[ "Bind", "a", "renderer", "to", "the", "given", "callable", "by", "constructing", "a", "new", "rendering", "view", "." ]
518d06f9ffd38dcacc0de4d94e72d1f8452157a8
https://github.com/Julian/Minion/blob/518d06f9ffd38dcacc0de4d94e72d1f8452157a8/minion/renderers.py#L61-L85
train
57,367
Formulka/django-fperms
fperms/__init__.py
get_perm_model
def get_perm_model(): """ Returns the Perm model that is active in this project. """ try: return django_apps.get_model(settings.PERM_MODEL, require_ready=False) except ValueError: raise ImproperlyConfigured("PERM_MODEL must be of the form 'app_label.model_name'") except LookupErr...
python
def get_perm_model(): """ Returns the Perm model that is active in this project. """ try: return django_apps.get_model(settings.PERM_MODEL, require_ready=False) except ValueError: raise ImproperlyConfigured("PERM_MODEL must be of the form 'app_label.model_name'") except LookupErr...
[ "def", "get_perm_model", "(", ")", ":", "try", ":", "return", "django_apps", ".", "get_model", "(", "settings", ".", "PERM_MODEL", ",", "require_ready", "=", "False", ")", "except", "ValueError", ":", "raise", "ImproperlyConfigured", "(", "\"PERM_MODEL must be of ...
Returns the Perm model that is active in this project.
[ "Returns", "the", "Perm", "model", "that", "is", "active", "in", "this", "project", "." ]
88b8fa3dd87075a56d8bfeb2b9993c578c22694e
https://github.com/Formulka/django-fperms/blob/88b8fa3dd87075a56d8bfeb2b9993c578c22694e/fperms/__init__.py#L9-L20
train
57,368
openstack/stacktach-winchester
winchester/config.py
ConfigManager._load_yaml_config
def _load_yaml_config(cls, config_data, filename="(unknown)"): """Load a yaml config file.""" try: config = yaml.safe_load(config_data) except yaml.YAMLError as err: if hasattr(err, 'problem_mark'): mark = err.problem_mark errmsg = ("Inval...
python
def _load_yaml_config(cls, config_data, filename="(unknown)"): """Load a yaml config file.""" try: config = yaml.safe_load(config_data) except yaml.YAMLError as err: if hasattr(err, 'problem_mark'): mark = err.problem_mark errmsg = ("Inval...
[ "def", "_load_yaml_config", "(", "cls", ",", "config_data", ",", "filename", "=", "\"(unknown)\"", ")", ":", "try", ":", "config", "=", "yaml", ".", "safe_load", "(", "config_data", ")", "except", "yaml", ".", "YAMLError", "as", "err", ":", "if", "hasattr"...
Load a yaml config file.
[ "Load", "a", "yaml", "config", "file", "." ]
54f3ffc4a8fd84b6fb29ad9b65adb018e8927956
https://github.com/openstack/stacktach-winchester/blob/54f3ffc4a8fd84b6fb29ad9b65adb018e8927956/winchester/config.py#L129-L150
train
57,369
dmaust/rounding
rounding/stochastic.py
sround
def sround(x, precision=0): """ Round a single number using default non-deterministic generator. @param x: to round. @param precision: decimal places to round. """ sr = StochasticRound(precision=precision) return sr.round(x)
python
def sround(x, precision=0): """ Round a single number using default non-deterministic generator. @param x: to round. @param precision: decimal places to round. """ sr = StochasticRound(precision=precision) return sr.round(x)
[ "def", "sround", "(", "x", ",", "precision", "=", "0", ")", ":", "sr", "=", "StochasticRound", "(", "precision", "=", "precision", ")", "return", "sr", ".", "round", "(", "x", ")" ]
Round a single number using default non-deterministic generator. @param x: to round. @param precision: decimal places to round.
[ "Round", "a", "single", "number", "using", "default", "non", "-", "deterministic", "generator", "." ]
06731dff803c30c0741e3199888e7e5266ad99cc
https://github.com/dmaust/rounding/blob/06731dff803c30c0741e3199888e7e5266ad99cc/rounding/stochastic.py#L58-L66
train
57,370
pignacio/chorddb
chorddb/tab/parser.py
_parse_chord_line
def _parse_chord_line(line): ''' Parse a chord line into a `ChordLineData` object. ''' chords = [ TabChord(position=position, chord=chord) for chord, position in Chord.extract_chordpos(line) ] return ChordLineData(chords=chords)
python
def _parse_chord_line(line): ''' Parse a chord line into a `ChordLineData` object. ''' chords = [ TabChord(position=position, chord=chord) for chord, position in Chord.extract_chordpos(line) ] return ChordLineData(chords=chords)
[ "def", "_parse_chord_line", "(", "line", ")", ":", "chords", "=", "[", "TabChord", "(", "position", "=", "position", ",", "chord", "=", "chord", ")", "for", "chord", ",", "position", "in", "Chord", ".", "extract_chordpos", "(", "line", ")", "]", "return"...
Parse a chord line into a `ChordLineData` object.
[ "Parse", "a", "chord", "line", "into", "a", "ChordLineData", "object", "." ]
e386e1f9251a01810f41f794eefa73151adca630
https://github.com/pignacio/chorddb/blob/e386e1f9251a01810f41f794eefa73151adca630/chorddb/tab/parser.py#L16-L22
train
57,371
pignacio/chorddb
chorddb/tab/parser.py
_get_line_type
def _get_line_type(line): ''' Decide the line type in function of its contents ''' stripped = line.strip() if not stripped: return 'empty' remainder = re.sub(r"\s+", " ", re.sub(CHORD_RE, "", stripped)) if len(remainder) * 2 < len(re.sub(r"\s+", " ", stripped)): return 'chord' re...
python
def _get_line_type(line): ''' Decide the line type in function of its contents ''' stripped = line.strip() if not stripped: return 'empty' remainder = re.sub(r"\s+", " ", re.sub(CHORD_RE, "", stripped)) if len(remainder) * 2 < len(re.sub(r"\s+", " ", stripped)): return 'chord' re...
[ "def", "_get_line_type", "(", "line", ")", ":", "stripped", "=", "line", ".", "strip", "(", ")", "if", "not", "stripped", ":", "return", "'empty'", "remainder", "=", "re", ".", "sub", "(", "r\"\\s+\"", ",", "\" \"", ",", "re", ".", "sub", "(", "CHORD...
Decide the line type in function of its contents
[ "Decide", "the", "line", "type", "in", "function", "of", "its", "contents" ]
e386e1f9251a01810f41f794eefa73151adca630
https://github.com/pignacio/chorddb/blob/e386e1f9251a01810f41f794eefa73151adca630/chorddb/tab/parser.py#L37-L45
train
57,372
pignacio/chorddb
chorddb/tab/parser.py
parse_line
def parse_line(line): ''' Parse a line into a `TabLine` object. ''' line = line.rstrip() line_type = _get_line_type(line) return TabLine( type=line_type, data=_DATA_PARSERS[line_type](line), original=line, )
python
def parse_line(line): ''' Parse a line into a `TabLine` object. ''' line = line.rstrip() line_type = _get_line_type(line) return TabLine( type=line_type, data=_DATA_PARSERS[line_type](line), original=line, )
[ "def", "parse_line", "(", "line", ")", ":", "line", "=", "line", ".", "rstrip", "(", ")", "line_type", "=", "_get_line_type", "(", "line", ")", "return", "TabLine", "(", "type", "=", "line_type", ",", "data", "=", "_DATA_PARSERS", "[", "line_type", "]", ...
Parse a line into a `TabLine` object.
[ "Parse", "a", "line", "into", "a", "TabLine", "object", "." ]
e386e1f9251a01810f41f794eefa73151adca630
https://github.com/pignacio/chorddb/blob/e386e1f9251a01810f41f794eefa73151adca630/chorddb/tab/parser.py#L48-L56
train
57,373
pignacio/chorddb
chorddb/tab/parser.py
parse_tablature
def parse_tablature(lines): ''' Parse a list of lines into a `Tablature`. ''' lines = [parse_line(l) for l in lines] return Tablature(lines=lines)
python
def parse_tablature(lines): ''' Parse a list of lines into a `Tablature`. ''' lines = [parse_line(l) for l in lines] return Tablature(lines=lines)
[ "def", "parse_tablature", "(", "lines", ")", ":", "lines", "=", "[", "parse_line", "(", "l", ")", "for", "l", "in", "lines", "]", "return", "Tablature", "(", "lines", "=", "lines", ")" ]
Parse a list of lines into a `Tablature`.
[ "Parse", "a", "list", "of", "lines", "into", "a", "Tablature", "." ]
e386e1f9251a01810f41f794eefa73151adca630
https://github.com/pignacio/chorddb/blob/e386e1f9251a01810f41f794eefa73151adca630/chorddb/tab/parser.py#L59-L62
train
57,374
a2liu/mr-clean
mr_clean/_utils/io.py
preview
def preview(df,preview_rows = 20):#,preview_max_cols = 0): """ Returns a preview of a dataframe, which contains both header rows and tail rows. """ if preview_rows < 4: preview_rows = 4 preview_rows = min(preview_rows,df.shape[0]) outer = math.floor(preview_rows / 4) return pd.concat...
python
def preview(df,preview_rows = 20):#,preview_max_cols = 0): """ Returns a preview of a dataframe, which contains both header rows and tail rows. """ if preview_rows < 4: preview_rows = 4 preview_rows = min(preview_rows,df.shape[0]) outer = math.floor(preview_rows / 4) return pd.concat...
[ "def", "preview", "(", "df", ",", "preview_rows", "=", "20", ")", ":", "#,preview_max_cols = 0):", "if", "preview_rows", "<", "4", ":", "preview_rows", "=", "4", "preview_rows", "=", "min", "(", "preview_rows", ",", "df", ".", "shape", "[", "0", "]", ")"...
Returns a preview of a dataframe, which contains both header rows and tail rows.
[ "Returns", "a", "preview", "of", "a", "dataframe", "which", "contains", "both", "header", "rows", "and", "tail", "rows", "." ]
0ee4ee5639f834dec4b59b94442fa84373f3c176
https://github.com/a2liu/mr-clean/blob/0ee4ee5639f834dec4b59b94442fa84373f3c176/mr_clean/_utils/io.py#L26-L36
train
57,375
a2liu/mr-clean
mr_clean/_utils/io.py
title_line
def title_line(text): """Returns a string that represents the text as a title blurb """ columns = shutil.get_terminal_size()[0] start = columns // 2 - len(text) // 2 output = '='*columns + '\n\n' + \ ' ' * start + str(text) + "\n\n" + \ '='*columns + '\n' return outpu...
python
def title_line(text): """Returns a string that represents the text as a title blurb """ columns = shutil.get_terminal_size()[0] start = columns // 2 - len(text) // 2 output = '='*columns + '\n\n' + \ ' ' * start + str(text) + "\n\n" + \ '='*columns + '\n' return outpu...
[ "def", "title_line", "(", "text", ")", ":", "columns", "=", "shutil", ".", "get_terminal_size", "(", ")", "[", "0", "]", "start", "=", "columns", "//", "2", "-", "len", "(", "text", ")", "//", "2", "output", "=", "'='", "*", "columns", "+", "'\\n\\...
Returns a string that represents the text as a title blurb
[ "Returns", "a", "string", "that", "represents", "the", "text", "as", "a", "title", "blurb" ]
0ee4ee5639f834dec4b59b94442fa84373f3c176
https://github.com/a2liu/mr-clean/blob/0ee4ee5639f834dec4b59b94442fa84373f3c176/mr_clean/_utils/io.py#L46-L55
train
57,376
dbuscher/pois
pois/__init__.py
RadiusGrid
def RadiusGrid(gridSize): """ Return a square grid with values of the distance from the centre of the grid to each gridpoint """ x,y=np.mgrid[0:gridSize,0:gridSize] x = x-(gridSize-1.0)/2.0 y = y-(gridSize-1.0)/2.0 return np.abs(x+1j*y)
python
def RadiusGrid(gridSize): """ Return a square grid with values of the distance from the centre of the grid to each gridpoint """ x,y=np.mgrid[0:gridSize,0:gridSize] x = x-(gridSize-1.0)/2.0 y = y-(gridSize-1.0)/2.0 return np.abs(x+1j*y)
[ "def", "RadiusGrid", "(", "gridSize", ")", ":", "x", ",", "y", "=", "np", ".", "mgrid", "[", "0", ":", "gridSize", ",", "0", ":", "gridSize", "]", "x", "=", "x", "-", "(", "gridSize", "-", "1.0", ")", "/", "2.0", "y", "=", "y", "-", "(", "g...
Return a square grid with values of the distance from the centre of the grid to each gridpoint
[ "Return", "a", "square", "grid", "with", "values", "of", "the", "distance", "from", "the", "centre", "of", "the", "grid", "to", "each", "gridpoint" ]
bb9d9a932e716b5d385221768027384691803aa3
https://github.com/dbuscher/pois/blob/bb9d9a932e716b5d385221768027384691803aa3/pois/__init__.py#L30-L38
train
57,377
dbuscher/pois
pois/__init__.py
CircularMaskGrid
def CircularMaskGrid(gridSize, diameter=None): """ Return a square grid with ones inside and zeros outside a given diameter circle """ if diameter is None: diameter=gridSize return np.less_equal(RadiusGrid(gridSize),diameter/2.0)
python
def CircularMaskGrid(gridSize, diameter=None): """ Return a square grid with ones inside and zeros outside a given diameter circle """ if diameter is None: diameter=gridSize return np.less_equal(RadiusGrid(gridSize),diameter/2.0)
[ "def", "CircularMaskGrid", "(", "gridSize", ",", "diameter", "=", "None", ")", ":", "if", "diameter", "is", "None", ":", "diameter", "=", "gridSize", "return", "np", ".", "less_equal", "(", "RadiusGrid", "(", "gridSize", ")", ",", "diameter", "/", "2.0", ...
Return a square grid with ones inside and zeros outside a given diameter circle
[ "Return", "a", "square", "grid", "with", "ones", "inside", "and", "zeros", "outside", "a", "given", "diameter", "circle" ]
bb9d9a932e716b5d385221768027384691803aa3
https://github.com/dbuscher/pois/blob/bb9d9a932e716b5d385221768027384691803aa3/pois/__init__.py#L41-L47
train
57,378
dbuscher/pois
pois/__init__.py
AdaptiveOpticsCorrect
def AdaptiveOpticsCorrect(pupils,diameter,maxRadial,numRemove=None): """ Correct a wavefront using Zernike rejection up to some maximal order. Can operate on multiple telescopes in parallel. Note that this version removes the piston mode as well """ gridSize=pupils.shape[-1] pupilsVector=np...
python
def AdaptiveOpticsCorrect(pupils,diameter,maxRadial,numRemove=None): """ Correct a wavefront using Zernike rejection up to some maximal order. Can operate on multiple telescopes in parallel. Note that this version removes the piston mode as well """ gridSize=pupils.shape[-1] pupilsVector=np...
[ "def", "AdaptiveOpticsCorrect", "(", "pupils", ",", "diameter", ",", "maxRadial", ",", "numRemove", "=", "None", ")", ":", "gridSize", "=", "pupils", ".", "shape", "[", "-", "1", "]", "pupilsVector", "=", "np", ".", "reshape", "(", "pupils", ",", "(", ...
Correct a wavefront using Zernike rejection up to some maximal order. Can operate on multiple telescopes in parallel. Note that this version removes the piston mode as well
[ "Correct", "a", "wavefront", "using", "Zernike", "rejection", "up", "to", "some", "maximal", "order", ".", "Can", "operate", "on", "multiple", "telescopes", "in", "parallel", ".", "Note", "that", "this", "version", "removes", "the", "piston", "mode", "as", "...
bb9d9a932e716b5d385221768027384691803aa3
https://github.com/dbuscher/pois/blob/bb9d9a932e716b5d385221768027384691803aa3/pois/__init__.py#L53-L69
train
57,379
dbuscher/pois
pois/__init__.py
FibreCouple
def FibreCouple(pupils,modeDiameter): """ Return the complex amplitudes coupled into a set of fibers """ gridSize=pupils.shape[-1] pupilsVector=np.reshape(pupils,(-1,gridSize**2)) mode=np.reshape(FibreMode(gridSize,modeDiameter),(gridSize**2,)) return np.inner(pupilsVector,mode)
python
def FibreCouple(pupils,modeDiameter): """ Return the complex amplitudes coupled into a set of fibers """ gridSize=pupils.shape[-1] pupilsVector=np.reshape(pupils,(-1,gridSize**2)) mode=np.reshape(FibreMode(gridSize,modeDiameter),(gridSize**2,)) return np.inner(pupilsVector,mode)
[ "def", "FibreCouple", "(", "pupils", ",", "modeDiameter", ")", ":", "gridSize", "=", "pupils", ".", "shape", "[", "-", "1", "]", "pupilsVector", "=", "np", ".", "reshape", "(", "pupils", ",", "(", "-", "1", ",", "gridSize", "**", "2", ")", ")", "mo...
Return the complex amplitudes coupled into a set of fibers
[ "Return", "the", "complex", "amplitudes", "coupled", "into", "a", "set", "of", "fibers" ]
bb9d9a932e716b5d385221768027384691803aa3
https://github.com/dbuscher/pois/blob/bb9d9a932e716b5d385221768027384691803aa3/pois/__init__.py#L81-L88
train
57,380
dbuscher/pois
pois/__init__.py
SingleModeCombine
def SingleModeCombine(pupils,modeDiameter=None): """ Return the instantaneous coherent fluxes and photometric fluxes for a multiway single-mode fibre combiner """ if modeDiameter is None: modeDiameter=0.9*pupils.shape[-1] amplitudes=FibreCouple(pupils,modeDiameter) cc=np.conj(amplitu...
python
def SingleModeCombine(pupils,modeDiameter=None): """ Return the instantaneous coherent fluxes and photometric fluxes for a multiway single-mode fibre combiner """ if modeDiameter is None: modeDiameter=0.9*pupils.shape[-1] amplitudes=FibreCouple(pupils,modeDiameter) cc=np.conj(amplitu...
[ "def", "SingleModeCombine", "(", "pupils", ",", "modeDiameter", "=", "None", ")", ":", "if", "modeDiameter", "is", "None", ":", "modeDiameter", "=", "0.9", "*", "pupils", ".", "shape", "[", "-", "1", "]", "amplitudes", "=", "FibreCouple", "(", "pupils", ...
Return the instantaneous coherent fluxes and photometric fluxes for a multiway single-mode fibre combiner
[ "Return", "the", "instantaneous", "coherent", "fluxes", "and", "photometric", "fluxes", "for", "a", "multiway", "single", "-", "mode", "fibre", "combiner" ]
bb9d9a932e716b5d385221768027384691803aa3
https://github.com/dbuscher/pois/blob/bb9d9a932e716b5d385221768027384691803aa3/pois/__init__.py#L90-L103
train
57,381
TimSC/python-oauth10a
oauth10a/__init__.py
to_unicode
def to_unicode(s): """ Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8. """ if not isinstance(s, TEXT): if not isinstance(s, bytes): raise TypeError('You are required to pass either unicode or ' 'bytes he...
python
def to_unicode(s): """ Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8. """ if not isinstance(s, TEXT): if not isinstance(s, bytes): raise TypeError('You are required to pass either unicode or ' 'bytes he...
[ "def", "to_unicode", "(", "s", ")", ":", "if", "not", "isinstance", "(", "s", ",", "TEXT", ")", ":", "if", "not", "isinstance", "(", "s", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'You are required to pass either unicode or '", "'bytes here, not: %r ...
Convert to unicode, raise exception with instructive error message if s is not unicode, ascii, or utf-8.
[ "Convert", "to", "unicode", "raise", "exception", "with", "instructive", "error", "message", "if", "s", "is", "not", "unicode", "ascii", "or", "utf", "-", "8", "." ]
f36fae0593f68891fd523f8f71e45695718bf054
https://github.com/TimSC/python-oauth10a/blob/f36fae0593f68891fd523f8f71e45695718bf054/oauth10a/__init__.py#L95-L112
train
57,382
TimSC/python-oauth10a
oauth10a/__init__.py
Request.to_postdata
def to_postdata(self): """Serialize as post data for a POST request.""" items = [] for k, v in sorted(self.items()): # predictable for testing items.append((k.encode('utf-8'), to_utf8_optional_iterator(v))) # tell urlencode to deal with sequence values and map them correctl...
python
def to_postdata(self): """Serialize as post data for a POST request.""" items = [] for k, v in sorted(self.items()): # predictable for testing items.append((k.encode('utf-8'), to_utf8_optional_iterator(v))) # tell urlencode to deal with sequence values and map them correctl...
[ "def", "to_postdata", "(", "self", ")", ":", "items", "=", "[", "]", "for", "k", ",", "v", "in", "sorted", "(", "self", ".", "items", "(", ")", ")", ":", "# predictable for testing", "items", ".", "append", "(", "(", "k", ".", "encode", "(", "'utf-...
Serialize as post data for a POST request.
[ "Serialize", "as", "post", "data", "for", "a", "POST", "request", "." ]
f36fae0593f68891fd523f8f71e45695718bf054
https://github.com/TimSC/python-oauth10a/blob/f36fae0593f68891fd523f8f71e45695718bf054/oauth10a/__init__.py#L419-L428
train
57,383
TimSC/python-oauth10a
oauth10a/__init__.py
Server.fetch_request_token
def fetch_request_token(self, oauth_request): """Processes a request_token request and returns the request token on success. """ try: # Get the request token for authorization. token = self._get_token(oauth_request, 'request') except Error: # N...
python
def fetch_request_token(self, oauth_request): """Processes a request_token request and returns the request token on success. """ try: # Get the request token for authorization. token = self._get_token(oauth_request, 'request') except Error: # N...
[ "def", "fetch_request_token", "(", "self", ",", "oauth_request", ")", ":", "try", ":", "# Get the request token for authorization.", "token", "=", "self", ".", "_get_token", "(", "oauth_request", ",", "'request'", ")", "except", "Error", ":", "# No token required for ...
Processes a request_token request and returns the request token on success.
[ "Processes", "a", "request_token", "request", "and", "returns", "the", "request", "token", "on", "success", "." ]
f36fae0593f68891fd523f8f71e45695718bf054
https://github.com/TimSC/python-oauth10a/blob/f36fae0593f68891fd523f8f71e45695718bf054/oauth10a/__init__.py#L734-L752
train
57,384
TimSC/python-oauth10a
oauth10a/__init__.py
Server.fetch_access_token
def fetch_access_token(self, oauth_request): """Processes an access_token request and returns the access token on success. """ version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) try: verifier = self._get_verifier(oauth_requ...
python
def fetch_access_token(self, oauth_request): """Processes an access_token request and returns the access token on success. """ version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) try: verifier = self._get_verifier(oauth_requ...
[ "def", "fetch_access_token", "(", "self", ",", "oauth_request", ")", ":", "version", "=", "self", ".", "_get_version", "(", "oauth_request", ")", "consumer", "=", "self", ".", "_get_consumer", "(", "oauth_request", ")", "try", ":", "verifier", "=", "self", "...
Processes an access_token request and returns the access token on success.
[ "Processes", "an", "access_token", "request", "and", "returns", "the", "access", "token", "on", "success", "." ]
f36fae0593f68891fd523f8f71e45695718bf054
https://github.com/TimSC/python-oauth10a/blob/f36fae0593f68891fd523f8f71e45695718bf054/oauth10a/__init__.py#L754-L768
train
57,385
TimSC/python-oauth10a
oauth10a/__init__.py
Server._get_token
def _get_token(self, oauth_request, token_type='access'): """Try to find the token for the provided request token key.""" token_field = oauth_request.get_parameter('oauth_token') token = self.data_store.lookup_token(token_type, token_field) if not token: raise OAuthError('Inv...
python
def _get_token(self, oauth_request, token_type='access'): """Try to find the token for the provided request token key.""" token_field = oauth_request.get_parameter('oauth_token') token = self.data_store.lookup_token(token_type, token_field) if not token: raise OAuthError('Inv...
[ "def", "_get_token", "(", "self", ",", "oauth_request", ",", "token_type", "=", "'access'", ")", ":", "token_field", "=", "oauth_request", ".", "get_parameter", "(", "'oauth_token'", ")", "token", "=", "self", ".", "data_store", ".", "lookup_token", "(", "toke...
Try to find the token for the provided request token key.
[ "Try", "to", "find", "the", "token", "for", "the", "provided", "request", "token", "key", "." ]
f36fae0593f68891fd523f8f71e45695718bf054
https://github.com/TimSC/python-oauth10a/blob/f36fae0593f68891fd523f8f71e45695718bf054/oauth10a/__init__.py#L812-L818
train
57,386
jkitzes/macroeco
macroeco/models/_curves.py
mete_upscale_iterative_alt
def mete_upscale_iterative_alt(S, N, doublings): """ This function is used to upscale from the anchor area. Parameters ---------- S : int or float Number of species at anchor scale N : int or float Number of individuals at anchor scale doublings : int Number of doubl...
python
def mete_upscale_iterative_alt(S, N, doublings): """ This function is used to upscale from the anchor area. Parameters ---------- S : int or float Number of species at anchor scale N : int or float Number of individuals at anchor scale doublings : int Number of doubl...
[ "def", "mete_upscale_iterative_alt", "(", "S", ",", "N", ",", "doublings", ")", ":", "# Arrays to store N and S at all doublings", "n_arr", "=", "np", ".", "empty", "(", "doublings", "+", "1", ")", "s_arr", "=", "np", ".", "empty", "(", "doublings", "+", "1"...
This function is used to upscale from the anchor area. Parameters ---------- S : int or float Number of species at anchor scale N : int or float Number of individuals at anchor scale doublings : int Number of doublings of A. Result vector will be length doublings + 1. R...
[ "This", "function", "is", "used", "to", "upscale", "from", "the", "anchor", "area", "." ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_curves.py#L576-L647
train
57,387
jkitzes/macroeco
macroeco/models/_curves.py
curve.fit_lsq
def fit_lsq(self, x, y_obs, params_start=None): """ Fit curve by method of least squares. Parameters ---------- x : iterable Independent variable y_obs : iterable Dependent variable (values observed at x) params_start : iterable ...
python
def fit_lsq(self, x, y_obs, params_start=None): """ Fit curve by method of least squares. Parameters ---------- x : iterable Independent variable y_obs : iterable Dependent variable (values observed at x) params_start : iterable ...
[ "def", "fit_lsq", "(", "self", ",", "x", ",", "y_obs", ",", "params_start", "=", "None", ")", ":", "# Set up variables", "x", "=", "np", ".", "atleast_1d", "(", "x", ")", "y_obs", "=", "np", ".", "atleast_1d", "(", "y_obs", ")", "if", "not", "params_...
Fit curve by method of least squares. Parameters ---------- x : iterable Independent variable y_obs : iterable Dependent variable (values observed at x) params_start : iterable Optional start values for all parameters. Default 1. Retu...
[ "Fit", "curve", "by", "method", "of", "least", "squares", "." ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_curves.py#L61-L111
train
57,388
jkitzes/macroeco
macroeco/models/_curves.py
mete_sar_gen.fit_lsq
def fit_lsq(self, df): """ Parameterize generic SAR curve from empirical data set Parameters ---------- df : DataFrame Result data frame from empirical SAR analysis Notes ----- Simply returns S0 and N0 from empirical SAR output, which are two...
python
def fit_lsq(self, df): """ Parameterize generic SAR curve from empirical data set Parameters ---------- df : DataFrame Result data frame from empirical SAR analysis Notes ----- Simply returns S0 and N0 from empirical SAR output, which are two...
[ "def", "fit_lsq", "(", "self", ",", "df", ")", ":", "tdf", "=", "df", ".", "set_index", "(", "'div'", ")", "return", "tdf", ".", "ix", "[", "'1,1'", "]", "[", "'n_spp'", "]", ",", "tdf", ".", "ix", "[", "'1,1'", "]", "[", "'n_individs'", "]" ]
Parameterize generic SAR curve from empirical data set Parameters ---------- df : DataFrame Result data frame from empirical SAR analysis Notes ----- Simply returns S0 and N0 from empirical SAR output, which are two fixed parameters of METE SAR and E...
[ "Parameterize", "generic", "SAR", "curve", "from", "empirical", "data", "set" ]
ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e
https://github.com/jkitzes/macroeco/blob/ee5fac5560a2d64de3a64738b5bc6833e2d7ff2e/macroeco/models/_curves.py#L548-L567
train
57,389
inveniosoftware-attic/invenio-comments
invenio_comments/models.py
after_insert
def after_insert(mapper, connection, target): """Update reply order cache and send record-after-update signal.""" record_after_update.send(CmtRECORDCOMMENT, recid=target.id_bibrec) from .api import get_reply_order_cache_data if target.in_reply_to_id_cmtRECORDCOMMENT > 0: parent = CmtRECORDCOMM...
python
def after_insert(mapper, connection, target): """Update reply order cache and send record-after-update signal.""" record_after_update.send(CmtRECORDCOMMENT, recid=target.id_bibrec) from .api import get_reply_order_cache_data if target.in_reply_to_id_cmtRECORDCOMMENT > 0: parent = CmtRECORDCOMM...
[ "def", "after_insert", "(", "mapper", ",", "connection", ",", "target", ")", ":", "record_after_update", ".", "send", "(", "CmtRECORDCOMMENT", ",", "recid", "=", "target", ".", "id_bibrec", ")", "from", ".", "api", "import", "get_reply_order_cache_data", "if", ...
Update reply order cache and send record-after-update signal.
[ "Update", "reply", "order", "cache", "and", "send", "record", "-", "after", "-", "update", "signal", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/models.py#L109-L126
train
57,390
inveniosoftware-attic/invenio-comments
invenio_comments/models.py
CmtRECORDCOMMENT.is_collapsed
def is_collapsed(self, id_user): """Return true if the comment is collapsed by user.""" return CmtCOLLAPSED.query.filter(db.and_( CmtCOLLAPSED.id_bibrec == self.id_bibrec, CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id, CmtCOLLAPSED.id_user == id_user)).count() > 0
python
def is_collapsed(self, id_user): """Return true if the comment is collapsed by user.""" return CmtCOLLAPSED.query.filter(db.and_( CmtCOLLAPSED.id_bibrec == self.id_bibrec, CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id, CmtCOLLAPSED.id_user == id_user)).count() > 0
[ "def", "is_collapsed", "(", "self", ",", "id_user", ")", ":", "return", "CmtCOLLAPSED", ".", "query", ".", "filter", "(", "db", ".", "and_", "(", "CmtCOLLAPSED", ".", "id_bibrec", "==", "self", ".", "id_bibrec", ",", "CmtCOLLAPSED", ".", "id_cmtRECORDCOMMENT...
Return true if the comment is collapsed by user.
[ "Return", "true", "if", "the", "comment", "is", "collapsed", "by", "user", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/models.py#L76-L81
train
57,391
inveniosoftware-attic/invenio-comments
invenio_comments/models.py
CmtRECORDCOMMENT.collapse
def collapse(self, id_user): """Collapse comment beloging to user.""" c = CmtCOLLAPSED(id_bibrec=self.id_bibrec, id_cmtRECORDCOMMENT=self.id, id_user=id_user) db.session.add(c) db.session.commit()
python
def collapse(self, id_user): """Collapse comment beloging to user.""" c = CmtCOLLAPSED(id_bibrec=self.id_bibrec, id_cmtRECORDCOMMENT=self.id, id_user=id_user) db.session.add(c) db.session.commit()
[ "def", "collapse", "(", "self", ",", "id_user", ")", ":", "c", "=", "CmtCOLLAPSED", "(", "id_bibrec", "=", "self", ".", "id_bibrec", ",", "id_cmtRECORDCOMMENT", "=", "self", ".", "id", ",", "id_user", "=", "id_user", ")", "db", ".", "session", ".", "ad...
Collapse comment beloging to user.
[ "Collapse", "comment", "beloging", "to", "user", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/models.py#L84-L89
train
57,392
inveniosoftware-attic/invenio-comments
invenio_comments/models.py
CmtRECORDCOMMENT.expand
def expand(self, id_user): """Expand comment beloging to user.""" CmtCOLLAPSED.query.filter(db.and_( CmtCOLLAPSED.id_bibrec == self.id_bibrec, CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id, CmtCOLLAPSED.id_user == id_user)).delete(synchronize_session=False)
python
def expand(self, id_user): """Expand comment beloging to user.""" CmtCOLLAPSED.query.filter(db.and_( CmtCOLLAPSED.id_bibrec == self.id_bibrec, CmtCOLLAPSED.id_cmtRECORDCOMMENT == self.id, CmtCOLLAPSED.id_user == id_user)).delete(synchronize_session=False)
[ "def", "expand", "(", "self", ",", "id_user", ")", ":", "CmtCOLLAPSED", ".", "query", ".", "filter", "(", "db", ".", "and_", "(", "CmtCOLLAPSED", ".", "id_bibrec", "==", "self", ".", "id_bibrec", ",", "CmtCOLLAPSED", ".", "id_cmtRECORDCOMMENT", "==", "self...
Expand comment beloging to user.
[ "Expand", "comment", "beloging", "to", "user", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/models.py#L91-L96
train
57,393
inveniosoftware-attic/invenio-comments
invenio_comments/models.py
CmtRECORDCOMMENT.count
def count(cls, *criteria, **filters): """Count how many comments.""" return cls.query.filter(*criteria).filter_by(**filters).count()
python
def count(cls, *criteria, **filters): """Count how many comments.""" return cls.query.filter(*criteria).filter_by(**filters).count()
[ "def", "count", "(", "cls", ",", "*", "criteria", ",", "*", "*", "filters", ")", ":", "return", "cls", ".", "query", ".", "filter", "(", "*", "criteria", ")", ".", "filter_by", "(", "*", "*", "filters", ")", ".", "count", "(", ")" ]
Count how many comments.
[ "Count", "how", "many", "comments", "." ]
62bb6e07c146baf75bf8de80b5896ab2a01a8423
https://github.com/inveniosoftware-attic/invenio-comments/blob/62bb6e07c146baf75bf8de80b5896ab2a01a8423/invenio_comments/models.py#L103-L105
train
57,394
aumayr/beancount-pygments-lexer
beancount_pygments_lexer/util/version.py
get_version
def get_version(version=None): """Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version[4] > 0: # 0.2.1-alpha.1 return "%s.%s.%s-%s.%s" % (version[0], version[1], version[2], version[3], version[4]) elif v...
python
def get_version(version=None): """Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided. """ if version[4] > 0: # 0.2.1-alpha.1 return "%s.%s.%s-%s.%s" % (version[0], version[1], version[2], version[3], version[4]) elif v...
[ "def", "get_version", "(", "version", "=", "None", ")", ":", "if", "version", "[", "4", "]", ">", "0", ":", "# 0.2.1-alpha.1", "return", "\"%s.%s.%s-%s.%s\"", "%", "(", "version", "[", "0", "]", ",", "version", "[", "1", "]", ",", "version", "[", "2"...
Returns a tuple of the django version. If version argument is non-empty, then checks for correctness of the tuple provided.
[ "Returns", "a", "tuple", "of", "the", "django", "version", ".", "If", "version", "argument", "is", "non", "-", "empty", "then", "checks", "for", "correctness", "of", "the", "tuple", "provided", "." ]
49ab7754a41fe850ebe88cb879ec0a78e1e06ef0
https://github.com/aumayr/beancount-pygments-lexer/blob/49ab7754a41fe850ebe88cb879ec0a78e1e06ef0/beancount_pygments_lexer/util/version.py#L1-L13
train
57,395
mixer/beam-interactive-python
beam_interactive/connection.py
Connection._push_packet
def _push_packet(self, packet): """ Appends a packet to the internal read queue, or notifies a waiting listener that a packet just came in. """ self._read_queue.append((decode(packet), packet)) if self._read_waiter is not None: w, self._read_waiter = self._re...
python
def _push_packet(self, packet): """ Appends a packet to the internal read queue, or notifies a waiting listener that a packet just came in. """ self._read_queue.append((decode(packet), packet)) if self._read_waiter is not None: w, self._read_waiter = self._re...
[ "def", "_push_packet", "(", "self", ",", "packet", ")", ":", "self", ".", "_read_queue", ".", "append", "(", "(", "decode", "(", "packet", ")", ",", "packet", ")", ")", "if", "self", ".", "_read_waiter", "is", "not", "None", ":", "w", ",", "self", ...
Appends a packet to the internal read queue, or notifies a waiting listener that a packet just came in.
[ "Appends", "a", "packet", "to", "the", "internal", "read", "queue", "or", "notifies", "a", "waiting", "listener", "that", "a", "packet", "just", "came", "in", "." ]
e035bc45515dea9315b77648a24b5ae8685aa5cf
https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/connection.py#L40-L49
train
57,396
mixer/beam-interactive-python
beam_interactive/connection.py
Connection._read_data
def _read_data(self): """ Reads data from the connection and adds it to _push_packet, until the connection is closed or the task in cancelled. """ while True: try: data = yield from self._socket.recv() except asyncio.CancelledError: ...
python
def _read_data(self): """ Reads data from the connection and adds it to _push_packet, until the connection is closed or the task in cancelled. """ while True: try: data = yield from self._socket.recv() except asyncio.CancelledError: ...
[ "def", "_read_data", "(", "self", ")", ":", "while", "True", ":", "try", ":", "data", "=", "yield", "from", "self", ".", "_socket", ".", "recv", "(", ")", "except", "asyncio", ".", "CancelledError", ":", "break", "except", "ConnectionClosed", ":", "break...
Reads data from the connection and adds it to _push_packet, until the connection is closed or the task in cancelled.
[ "Reads", "data", "from", "the", "connection", "and", "adds", "it", "to", "_push_packet", "until", "the", "connection", "is", "closed", "or", "the", "task", "in", "cancelled", "." ]
e035bc45515dea9315b77648a24b5ae8685aa5cf
https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/connection.py#L52-L67
train
57,397
mixer/beam-interactive-python
beam_interactive/connection.py
Connection.wait_message
def wait_message(self): """ Waits until a connection is available on the wire, or until the connection is in a state that it can't accept messages. It returns True if a message is available, False otherwise. """ if self._state != states['open']: return False ...
python
def wait_message(self): """ Waits until a connection is available on the wire, or until the connection is in a state that it can't accept messages. It returns True if a message is available, False otherwise. """ if self._state != states['open']: return False ...
[ "def", "wait_message", "(", "self", ")", ":", "if", "self", ".", "_state", "!=", "states", "[", "'open'", "]", ":", "return", "False", "if", "len", "(", "self", ".", "_read_queue", ")", ">", "0", ":", "return", "True", "assert", "self", ".", "_read_w...
Waits until a connection is available on the wire, or until the connection is in a state that it can't accept messages. It returns True if a message is available, False otherwise.
[ "Waits", "until", "a", "connection", "is", "available", "on", "the", "wire", "or", "until", "the", "connection", "is", "in", "a", "state", "that", "it", "can", "t", "accept", "messages", ".", "It", "returns", "True", "if", "a", "message", "is", "availabl...
e035bc45515dea9315b77648a24b5ae8685aa5cf
https://github.com/mixer/beam-interactive-python/blob/e035bc45515dea9315b77648a24b5ae8685aa5cf/beam_interactive/connection.py#L70-L86
train
57,398
QualiSystems/CloudShell-Traffic
cloudshell/traffic/tg_helper.py
get_reservation_ports
def get_reservation_ports(session, reservation_id, model_name='Generic Traffic Generator Port'): """ Get all Generic Traffic Generator Port in reservation. :return: list of all Generic Traffic Generator Port resource objects in reservation """ reservation_ports = [] reservation = session.GetReserv...
python
def get_reservation_ports(session, reservation_id, model_name='Generic Traffic Generator Port'): """ Get all Generic Traffic Generator Port in reservation. :return: list of all Generic Traffic Generator Port resource objects in reservation """ reservation_ports = [] reservation = session.GetReserv...
[ "def", "get_reservation_ports", "(", "session", ",", "reservation_id", ",", "model_name", "=", "'Generic Traffic Generator Port'", ")", ":", "reservation_ports", "=", "[", "]", "reservation", "=", "session", ".", "GetReservationDetails", "(", "reservation_id", ")", "....
Get all Generic Traffic Generator Port in reservation. :return: list of all Generic Traffic Generator Port resource objects in reservation
[ "Get", "all", "Generic", "Traffic", "Generator", "Port", "in", "reservation", "." ]
4579d42e359fa9d5736dc4ceb8d86547f0e7120d
https://github.com/QualiSystems/CloudShell-Traffic/blob/4579d42e359fa9d5736dc4ceb8d86547f0e7120d/cloudshell/traffic/tg_helper.py#L24-L35
train
57,399