text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_texts_and_labels(sentence_chunk): """Given a sentence chunk, extract original texts and labels.""" words = sentence_chunk.split('\n') texts = [] labels = [] for word in words: word = word.strip() if len(word) > 0: toks = word.split('\t') texts.append(t...
[ "def", "get_texts_and_labels", "(", "sentence_chunk", ")", ":", "words", "=", "sentence_chunk", ".", "split", "(", "'\\n'", ")", "texts", "=", "[", "]", "labels", "=", "[", "]", "for", "word", "in", "words", ":", "word", "=", "word", ".", "strip", "(",...
32.75
0.002475
def translate(word, config, use_cache=True, to_eng=False): """Translate a word. Parameters ---------- word : str Word to translate. config : Config Configuration settings. use_cache : bool, optional Wheter to use cache. to_eng : bool, optional Translate from ...
[ "def", "translate", "(", "word", ",", "config", ",", "use_cache", "=", "True", ",", "to_eng", "=", "False", ")", ":", "translation", "=", "None", "data_dir", "=", "Path", "(", "config", "[", "\"data dir\"", "]", ")", "if", "use_cache", ":", "logger", "...
22.166667
0.0009
def census(self, *scales): """Current World Census data. By default returns data on today's featured World Census scale, use arguments to get results on specific scales. In order to request data on all scales at once you can do ``x.census(*range(81))``. Parameters ...
[ "def", "census", "(", "self", ",", "*", "scales", ")", ":", "params", "=", "{", "'mode'", ":", "'score+rank+rrank+prank+prrank'", "}", "if", "scales", ":", "params", "[", "'scale'", "]", "=", "'+'", ".", "join", "(", "str", "(", "x", ")", "for", "x",...
31.892857
0.002174
def postcmd(self, stop, line): ''' Exit cmd cleanly. ''' self.color_prompt() return Cmd.postcmd(self, stop, line)
[ "def", "postcmd", "(", "self", ",", "stop", ",", "line", ")", ":", "self", ".", "color_prompt", "(", ")", "return", "Cmd", ".", "postcmd", "(", "self", ",", "stop", ",", "line", ")" ]
33.5
0.014599
def add_router_to_hosting_device(self, context, hosting_device_id, router_id): """Add a (non-hosted) router to a hosting device.""" e_context = context.elevated() r_hd_binding_db = self._get_router_binding_info(e_context, router_id) if r_hd_binding_db...
[ "def", "add_router_to_hosting_device", "(", "self", ",", "context", ",", "hosting_device_id", ",", "router_id", ")", ":", "e_context", "=", "context", ".", "elevated", "(", ")", "r_hd_binding_db", "=", "self", ".", "_get_router_binding_info", "(", "e_context", ","...
54.814815
0.001992
def _init_io(self): """! GPIO initialization. Set GPIO into BCM mode and init other IOs mode """ GPIO.setwarnings(False) GPIO.setmode( GPIO.BCM ) pins = [ self._spi_dc ] for pin in pins: GPIO.setup( pin, GPIO.OUT )
[ "def", "_init_io", "(", "self", ")", ":", "GPIO", ".", "setwarnings", "(", "False", ")", "GPIO", ".", "setmode", "(", "GPIO", ".", "BCM", ")", "pins", "=", "[", "self", ".", "_spi_dc", "]", "for", "pin", "in", "pins", ":", "GPIO", ".", "setup", "...
28.1
0.027586
def _canvas_route(self, *args, **kwargs): """ Decorator for canvas route """ def outer(view_fn): @self.route(*args, **kwargs) def inner(*args, **kwargs): fn_args = getargspec(view_fn) try: idx = fn_args.args.index(_ARG_KEY) except ValueErr...
[ "def", "_canvas_route", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "outer", "(", "view_fn", ")", ":", "@", "self", ".", "route", "(", "*", "args", ",", "*", "*", "kwargs", ")", "def", "inner", "(", "*", "args", ","...
36.489362
0.001704
def get_log_stream(logger): """ Returns a stream to the root log file. If there is no logfile return the stderr log stream Returns: A stream to the root log file or stderr stream. """ file_stream = None log_stream = None for handler in logger.handlers: if isinstance(han...
[ "def", "get_log_stream", "(", "logger", ")", ":", "file_stream", "=", "None", "log_stream", "=", "None", "for", "handler", "in", "logger", ".", "handlers", ":", "if", "isinstance", "(", "handler", ",", "logging", ".", "FileHandler", ")", ":", "file_stream", ...
23.47619
0.001949
def list_bundled_profiles(): """list profiles that are bundled with IPython.""" path = os.path.join(get_ipython_package_dir(), u'config', u'profile') files = os.listdir(path) profiles = [] for profile in files: full_path = os.path.join(path, profile) if os.path.isdir(full_path) and p...
[ "def", "list_bundled_profiles", "(", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "get_ipython_package_dir", "(", ")", ",", "u'config'", ",", "u'profile'", ")", "files", "=", "os", ".", "listdir", "(", "path", ")", "profiles", "=", "[", ...
39.2
0.002494
def add_param_summary(*summary_lists, **kwargs): """ Add summary ops for all trainable variables matching the regex, under a reused 'param-summary' name scope. This function is a no-op if not calling from main training tower. Args: summary_lists (list): each is (regex, [list of summary type...
[ "def", "add_param_summary", "(", "*", "summary_lists", ",", "*", "*", "kwargs", ")", ":", "collections", "=", "kwargs", ".", "pop", "(", "'collections'", ",", "None", ")", "assert", "len", "(", "kwargs", ")", "==", "0", ",", "\"Unknown kwargs: \"", "+", ...
35.2
0.00158
def wvcal_spectrum(sp, fxpeaks, poly_degree_wfit, wv_master, wv_ini_search=None, wv_end_search=None, wvmin_useful=None, wvmax_useful=None, geometry=None, debugplot=0): """Execute wavelength calibration of a spectrum using fixed line peaks. Parameters ...
[ "def", "wvcal_spectrum", "(", "sp", ",", "fxpeaks", ",", "poly_degree_wfit", ",", "wv_master", ",", "wv_ini_search", "=", "None", ",", "wv_end_search", "=", "None", ",", "wvmin_useful", "=", "None", ",", "wvmax_useful", "=", "None", ",", "geometry", "=", "No...
33.694915
0.000244
def get_plot(self, units='THz', ymin=None, ymax=None, width=None, height=None, dpi=None, plt=None, fonts=None, dos=None, dos_aspect=3, color=None, style=None, no_base_style=False): """Get a :obj:`matplotlib.pyplot` object of the phonon band structure. Args: ...
[ "def", "get_plot", "(", "self", ",", "units", "=", "'THz'", ",", "ymin", "=", "None", ",", "ymax", "=", "None", ",", "width", "=", "None", ",", "height", "=", "None", ",", "dpi", "=", "None", ",", "plt", "=", "None", ",", "fonts", "=", "None", ...
47.215385
0.001277
def safe_get(dictionary, key, default_value, can_return_none=True): """ Safely perform a dictionary get, returning the default value if the key is not found. :param dict dictionary: the dictionary :param string key: the key :param variant default_value: the default value to be returned :par...
[ "def", "safe_get", "(", "dictionary", ",", "key", ",", "default_value", ",", "can_return_none", "=", "True", ")", ":", "return_value", "=", "default_value", "try", ":", "return_value", "=", "dictionary", "[", "key", "]", "if", "(", "return_value", "is", "Non...
38.695652
0.002193
def compute_affinity_matrix(self, copy=False, **kwargs): """ This function will compute the affinity matrix. In order to acquire the existing affinity matrix use self.affinity_matrix as comptute_affinity_matrix() will re-compute the affinity matrix. Parameters ----------...
[ "def", "compute_affinity_matrix", "(", "self", ",", "copy", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "adjacency_matrix", "is", "None", ":", "self", ".", "compute_adjacency_matrix", "(", ")", "kwds", "=", "self", ".", "affinity_kw...
38.806452
0.001622
def user_info(access_token, request): """ Return basic information about a user. Limited to OAuth clients that have receieved authorization to the 'user_info' scope. """ user = access_token.user data = { 'username': user.username, 'first_name': user.first_name, 'last_name': user.last_name...
[ "def", "user_info", "(", "access_token", ",", "request", ")", ":", "user", "=", "access_token", ".", "user", "data", "=", "{", "'username'", ":", "user", ".", "username", ",", "'first_name'", ":", "user", ".", "first_name", ",", "'last_name'", ":", "user",...
29.4375
0.010288
def child_removed(self, child): """ Reset the item cache when a child is removed """ super(AbstractWidgetItemGroup, self).child_removed(child) self.get_member('_items').reset(self)
[ "def", "child_removed", "(", "self", ",", "child", ")", ":", "super", "(", "AbstractWidgetItemGroup", ",", "self", ")", ".", "child_removed", "(", "child", ")", "self", ".", "get_member", "(", "'_items'", ")", ".", "reset", "(", "self", ")" ]
50.25
0.009804
def update(args): """ Run site update --------------- Run updates for site or all installed. :: usage: main.py update [-h] [-v] [-p PATH] [SITE] Run site update positional arguments: SITE Path to site or name (project.branch) optional ar...
[ "def", "update", "(", "args", ")", ":", "if", "args", ".", "SITE", ":", "site", "=", "find_site", "(", "args", ".", "SITE", ",", "path", "=", "args", ".", "path", ")", "return", "site", ".", "run_update", "(", ")", "for", "site", "in", "gen_sites",...
21.930233
0.00203
def respond_from_user_question(self, user_question, importance): """Respond to a question in exactly the way that is described by the given user_question. :param user_question: The user question to respond with. :type user_question: :class:`.UserQuestion` :param importance: The ...
[ "def", "respond_from_user_question", "(", "self", ",", "user_question", ",", "importance", ")", ":", "user_response_ids", "=", "[", "option", ".", "id", "for", "option", "in", "user_question", ".", "answer_options", "if", "option", ".", "is_users", "]", "match_r...
52.47619
0.001783
def mailcap_find_match(self, *args, **kwargs): """ Propagates :func:`mailcap.find_match` but caches the mailcap (first argument) """ return mailcap.findmatch(self._mailcaps, *args, **kwargs)
[ "def", "mailcap_find_match", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "mailcap", ".", "findmatch", "(", "self", ".", "_mailcaps", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
37.5
0.008696
def diffplot(self, f, delay=1, lfilter=None, **kargs): """diffplot(f, delay=1, lfilter=None) Applies a function to couples (l[i],l[i+delay]) A list of matplotlib.lines.Line2D is returned. """ # Get the list of packets if lfilter is None: lst_pkts = [f(self.r...
[ "def", "diffplot", "(", "self", ",", "f", ",", "delay", "=", "1", ",", "lfilter", "=", "None", ",", "*", "*", "kargs", ")", ":", "# Get the list of packets", "if", "lfilter", "is", "None", ":", "lst_pkts", "=", "[", "f", "(", "self", ".", "res", "[...
32.923077
0.00227
def check_connection(self): """Resolve hostname.""" host = self.urlparts[1] addresses = socket.getaddrinfo(host, 80, 0, 0, socket.SOL_TCP) args = {'host': host} if addresses: args['ips'] = [x[4][0] for x in addresses] self.set_result(_('%(host)s resolved t...
[ "def", "check_connection", "(", "self", ")", ":", "host", "=", "self", ".", "urlparts", "[", "1", "]", "addresses", "=", "socket", ".", "getaddrinfo", "(", "host", ",", "80", ",", "0", ",", "0", ",", "socket", ".", "SOL_TCP", ")", "args", "=", "{",...
44.5
0.008811
def timeline_home(self, max_id=None, min_id=None, since_id=None, limit=None): """ Fetch the logged-in users home timeline (i.e. followed users and self). Returns a list of `toot dicts`_. """ return self.timeline('home', max_id=max_id, min_id=min_id, ...
[ "def", "timeline_home", "(", "self", ",", "max_id", "=", "None", ",", "min_id", "=", "None", ",", "since_id", "=", "None", ",", "limit", "=", "None", ")", ":", "return", "self", ".", "timeline", "(", "'home'", ",", "max_id", "=", "max_id", ",", "min_...
43.125
0.008523
def _lmder1_powell_singular(): """Powell's singular function (lmder test #6). Don't run this as a test, since it just zooms to zero parameters. The precise results depend a lot on nitty-gritty rounding and tolerances and things.""" def func(params, vec): vec[0] = params[0] + 10 * params[1] ...
[ "def", "_lmder1_powell_singular", "(", ")", ":", "def", "func", "(", "params", ",", "vec", ")", ":", "vec", "[", "0", "]", "=", "params", "[", "0", "]", "+", "10", "*", "params", "[", "1", "]", "vec", "[", "1", "]", "=", "np", ".", "sqrt", "(...
34.851852
0.011375
def _report_final_failure(self, err, flaky, name): """ Report that the test has failed too many times to pass at least min_passes times. By default, this means that the test has failed twice. :param err: Information about the test failure (from sys.exc_info()) ...
[ "def", "_report_final_failure", "(", "self", ",", "err", ",", "flaky", ",", "name", ")", ":", "min_passes", "=", "flaky", "[", "FlakyNames", ".", "MIN_PASSES", "]", "current_passes", "=", "flaky", "[", "FlakyNames", ".", "CURRENT_PASSES", "]", "message", "="...
32.185185
0.002235
def _get_report_id(self): """Returns a hash of the reports JSON file """ if self.watch: # Searches for the first occurence of the nextflow pipeline # file name in the .nextflow.log file pipeline_path = get_nextflow_filepath(self.log_file) # Get ...
[ "def", "_get_report_id", "(", "self", ")", ":", "if", "self", ".", "watch", ":", "# Searches for the first occurence of the nextflow pipeline", "# file name in the .nextflow.log file", "pipeline_path", "=", "get_nextflow_filepath", "(", "self", ".", "log_file", ")", "# Get ...
39.324324
0.002012
def _gen_mask(num_blocks, n_in, n_out, mask_type=MASK_EXCLUSIVE, dtype=tf.float32): """Generate the mask for building an autoregressive dense layer.""" # TODO(b/67594795): Better support of dynamic shape. mask = np.zeros([n_out, n_in], dtype=dtype.as_numpy_d...
[ "def", "_gen_mask", "(", "num_blocks", ",", "n_in", ",", "n_out", ",", "mask_type", "=", "MASK_EXCLUSIVE", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "# TODO(b/67594795): Better support of dynamic shape.", "mask", "=", "np", ".", "zeros", "(", "[", "n_...
39.5
0.014433
def sortmerna_detailed_barplot (self): """ Make the HighCharts HTML to plot the sortmerna rates """ # Specify the order of the different possible categories keys = OrderedDict() metrics = set() for sample in self.sortmerna: for key in self.sortmerna[sample]: ...
[ "def", "sortmerna_detailed_barplot", "(", "self", ")", ":", "# Specify the order of the different possible categories", "keys", "=", "OrderedDict", "(", ")", "metrics", "=", "set", "(", ")", "for", "sample", "in", "self", ".", "sortmerna", ":", "for", "key", "in",...
34.590909
0.015345
def _JzIntegrand(z,Ez,pot): """The J_z integrand""" return nu.sqrt(2.*(Ez-potentialVertical(z,pot)))
[ "def", "_JzIntegrand", "(", "z", ",", "Ez", ",", "pot", ")", ":", "return", "nu", ".", "sqrt", "(", "2.", "*", "(", "Ez", "-", "potentialVertical", "(", "z", ",", "pot", ")", ")", ")" ]
35.333333
0.037037
def install_python_module_locally(name): """ instals a python module using pip """ with settings(hide('everything'), warn_only=False, capture=True): # convert 0 into True, any errors will always raise an exception print(not bool(local('pip --quiet install %s' % name).return_cod...
[ "def", "install_python_module_locally", "(", "name", ")", ":", "with", "settings", "(", "hide", "(", "'everything'", ")", ",", "warn_only", "=", "False", ",", "capture", "=", "True", ")", ":", "# convert 0 into True, any errors will always raise an exception", "print"...
50.625
0.002427
def epochs(self): """Get epochs as generator Returns ------- list of dict each epoch is defined by start_time and end_time (in s in reference to the start of the recordings) and a string of the sleep stage, and a string of the signal quality. ...
[ "def", "epochs", "(", "self", ")", ":", "if", "self", ".", "rater", "is", "None", ":", "raise", "IndexError", "(", "'You need to have at least one rater'", ")", "for", "one_epoch", "in", "self", ".", "rater", ".", "iterfind", "(", "'stages/epoch'", ")", ":",...
37.259259
0.001938
def RybToRgb(hue): '''Maps a hue on Itten's RYB color wheel to the standard RGB wheel. Parameters: :hue: The hue on Itten's RYB color wheel [0...360] Returns: An approximation of the corresponding hue on the standard RGB wheel. >>> Color.RybToRgb(15) 8.0 ''' d = hue %...
[ "def", "RybToRgb", "(", "hue", ")", ":", "d", "=", "hue", "%", "15", "i", "=", "int", "(", "hue", "/", "15", ")", "x0", "=", "_RgbWheel", "[", "i", "]", "x1", "=", "_RgbWheel", "[", "i", "+", "1", "]", "return", "x0", "+", "(", "x1", "-", ...
21.368421
0.002358
def _read_hdr(self): """Read header from EDF file. It only reads the header for internal purposes and adds a hdr. """ with self.filename.open('rb') as f: hdr = {} assert f.tell() == 0 assert f.read(8) == b'0 ' # recording info ...
[ "def", "_read_hdr", "(", "self", ")", ":", "with", "self", ".", "filename", ".", "open", "(", "'rb'", ")", "as", "f", ":", "hdr", "=", "{", "}", "assert", "f", ".", "tell", "(", ")", "==", "0", "assert", "f", ".", "read", "(", "8", ")", "==",...
37.893939
0.002338
async def setRemoteDescription(self, sessionDescription): """ Changes the remote description associated with the connection. :param: sessionDescription: An :class:`RTCSessionDescription` created from information received over the signaling channel. ""...
[ "async", "def", "setRemoteDescription", "(", "self", ",", "sessionDescription", ")", ":", "# parse and validate description", "description", "=", "sdp", ".", "SessionDescription", ".", "parse", "(", "sessionDescription", ".", "sdp", ")", "description", ".", "type", ...
44.147059
0.001466
def configure_volume(before_change=lambda: None, after_change=lambda: None): '''Set up storage (or don't) according to the charm's volume configuration. Returns the mount point or "ephemeral". before_change and after_change are optional functions to be called if the volume configuration changes. '...
[ "def", "configure_volume", "(", "before_change", "=", "lambda", ":", "None", ",", "after_change", "=", "lambda", ":", "None", ")", ":", "config", "=", "get_config", "(", ")", "if", "not", "config", ":", "hookenv", ".", "log", "(", "'Failed to read volume con...
36.483871
0.000861
def render_to_response(self, context, **response_kwargs): """ Returns a JSON response, transforming 'context' to make the payload. """ serializer = GeoJSONSerializer() response = self.response_class(**response_kwargs) queryset = self.get_queryset() options = dict...
[ "def", "render_to_response", "(", "self", ",", "context", ",", "*", "*", "response_kwargs", ")", ":", "serializer", "=", "GeoJSONSerializer", "(", ")", "response", "=", "self", ".", "response_class", "(", "*", "*", "response_kwargs", ")", "queryset", "=", "s...
43.666667
0.002134
def from_file(self, fname, binary=False, **kwargs): """ Initialize the class instance from gridded data in a file. Usage ----- x = SHGrid.from_file(fname, [binary, **kwargs]) Returns ------- x : SHGrid class instance Parameters ---------...
[ "def", "from_file", "(", "self", ",", "fname", ",", "binary", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "binary", "is", "False", ":", "data", "=", "_np", ".", "loadtxt", "(", "fname", ",", "*", "*", "kwargs", ")", "elif", "binary", "...
39.611111
0.000912
def fact_pk(self): """ Try to determine the primary key of the fact table for use in fact table counting. If more than one column exists, return the first column of the pk. """ keys = [c for c in self.fact_table.columns if c.primary_key] return keys[0]
[ "def", "fact_pk", "(", "self", ")", ":", "keys", "=", "[", "c", "for", "c", "in", "self", ".", "fact_table", ".", "columns", "if", "c", ".", "primary_key", "]", "return", "keys", "[", "0", "]" ]
42.142857
0.009967
def get_covaried_params(mus, evecsCV): """ Function to rotate from position(s) in the mu_i coordinate system into the position(s) in the xi_i coordinate system Parameters ----------- mus : list of floats or numpy.arrays Position of the system(s) in the mu coordinate system evecsCV :...
[ "def", "get_covaried_params", "(", "mus", ",", "evecsCV", ")", ":", "mus", "=", "numpy", ".", "array", "(", "mus", ",", "copy", "=", "False", ")", "# If original inputs were floats we need to make this a 2D array", "if", "len", "(", "mus", ".", "shape", ")", "...
27.40625
0.002203
def next(self): """Get next data batch from iterator. Returns ------- DataBatch The data of next batch. Raises ------ StopIteration If the end of the data is reached. """ if self.iter_next(): return DataBatch(d...
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "iter_next", "(", ")", ":", "return", "DataBatch", "(", "data", "=", "self", ".", "getdata", "(", ")", ",", "label", "=", "self", ".", "getlabel", "(", ")", ",", "pad", "=", "self", ".", ...
25.277778
0.008475
async def del_alternative(self, alt, timeout=OTGW_DEFAULT_TIMEOUT): """ Remove the specified Data-ID from the list of alternative commands. Only one occurrence is deleted. If the Data-ID appears multiple times in the list of alternative commands, this command must be repeated to ...
[ "async", "def", "del_alternative", "(", "self", ",", "alt", ",", "timeout", "=", "OTGW_DEFAULT_TIMEOUT", ")", ":", "cmd", "=", "OTGW_CMD_DEL_ALT", "alt", "=", "int", "(", "alt", ")", "if", "alt", "<", "1", "or", "alt", ">", "255", ":", "return", "None"...
41.52381
0.002242
def set_setting(self, setting, value, area='1', validate_value=True): """Set an abode system setting to a given value.""" setting = setting.lower() if setting not in CONST.ALL_SETTINGS: raise AbodeException(ERROR.INVALID_SETTING, CONST.ALL_SETTINGS) if setting in CONST.PANE...
[ "def", "set_setting", "(", "self", ",", "setting", ",", "value", ",", "area", "=", "'1'", ",", "validate_value", "=", "True", ")", ":", "setting", "=", "setting", ".", "lower", "(", ")", "if", "setting", "not", "in", "CONST", ".", "ALL_SETTINGS", ":", ...
45.47619
0.002051
def history_view(self, request, object_id, extra_context=None): from django.template.response import TemplateResponse from django.contrib.admin.options import get_content_type_for_model from django.contrib.admin.utils import unquote from django.core.exceptions import PermissionDenied ...
[ "def", "history_view", "(", "self", ",", "request", ",", "object_id", ",", "extra_context", "=", "None", ")", ":", "from", "django", ".", "template", ".", "response", "import", "TemplateResponse", "from", "django", ".", "contrib", ".", "admin", ".", "options...
42.630435
0.001496
def _add_relations(self, relations): """Add all of the relations for the services.""" for k, v in six.iteritems(relations): self.d.relate(k, v)
[ "def", "_add_relations", "(", "self", ",", "relations", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "relations", ")", ":", "self", ".", "d", ".", "relate", "(", "k", ",", "v", ")" ]
42
0.011696
def init_and_start(self, taskParent, override={}): """Convenience method to initialize and start a task. """ tag = self.initialize(taskParent, override=override) self.start() return tag
[ "def", "init_and_start", "(", "self", ",", "taskParent", ",", "override", "=", "{", "}", ")", ":", "tag", "=", "self", ".", "initialize", "(", "taskParent", ",", "override", "=", "override", ")", "self", ".", "start", "(", ")", "return", "tag" ]
31.428571
0.00885
def plot_metric(booster, metric=None, dataset_names=None, ax=None, xlim=None, ylim=None, title='Metric during training', xlabel='Iterations', ylabel='auto', figsize=None, grid=True): """Plot one metric during training. Parameters ---------- ...
[ "def", "plot_metric", "(", "booster", ",", "metric", "=", "None", ",", "dataset_names", "=", "None", ",", "ax", "=", "None", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "title", "=", "'Metric during training'", ",", "xlabel", "=", "'Iteratio...
35.655738
0.001566
def to_file(self, path): """Write metadata to an image, video or XMP sidecar file. :param str path: The image/video file path name. """ xmp_path = path + '.xmp' # remove any existing XMP file if os.path.exists(xmp_path): os.unlink(xmp_path) # attempt...
[ "def", "to_file", "(", "self", ",", "path", ")", ":", "xmp_path", "=", "path", "+", "'.xmp'", "# remove any existing XMP file", "if", "os", ".", "path", ".", "exists", "(", "xmp_path", ")", ":", "os", ".", "unlink", "(", "xmp_path", ")", "# attempt to open...
35.454545
0.001248
def find_lines(self, line): """Find all lines matching a given line.""" for other_line in self.lines: if other_line.match(line): yield other_line
[ "def", "find_lines", "(", "self", ",", "line", ")", ":", "for", "other_line", "in", "self", ".", "lines", ":", "if", "other_line", ".", "match", "(", "line", ")", ":", "yield", "other_line" ]
37
0.010582
def has_edit_permission(self, request): """ Can edit this object """ return request.user.is_authenticated and request.user.is_active and request.user.is_staff
[ "def", "has_edit_permission", "(", "self", ",", "request", ")", ":", "return", "request", ".", "user", ".", "is_authenticated", "and", "request", ".", "user", ".", "is_active", "and", "request", ".", "user", ".", "is_staff" ]
57.333333
0.017241
def print_stats(self): """ Print a series of relevant stats about a full execution. This function is meant to be called at the end of the program. """ stats = self.calculate() total_time = '%d:%02d:%02d' % (stats['total_time'] / 3600, ...
[ "def", "print_stats", "(", "self", ")", ":", "stats", "=", "self", ".", "calculate", "(", ")", "total_time", "=", "'%d:%02d:%02d'", "%", "(", "stats", "[", "'total_time'", "]", "/", "3600", ",", "(", "stats", "[", "'total_time'", "]", "/", "3600", ")",...
46.590909
0.000956
def server_socket(self, config): """ :meth:`.WNetworkNativeTransportProto.server_socket` method implementation """ if self.__server_socket is None: self.__server_socket = self.create_server_socket(config) self.__server_socket.bind(self.bind_socket(config).pair()) return self.__server_socket
[ "def", "server_socket", "(", "self", ",", "config", ")", ":", "if", "self", ".", "__server_socket", "is", "None", ":", "self", ".", "__server_socket", "=", "self", ".", "create_server_socket", "(", "config", ")", "self", ".", "__server_socket", ".", "bind", ...
42.714286
0.02623
def asList(self): """ returns a Point value as a list of [x,y,<z>,<m>] """ base = [self._x, self._y] if not self._z is None: base.append(self._z) elif not self._m is None: base.append(self._m) return base
[ "def", "asList", "(", "self", ")", ":", "base", "=", "[", "self", ".", "_x", ",", "self", ".", "_y", "]", "if", "not", "self", ".", "_z", "is", "None", ":", "base", ".", "append", "(", "self", ".", "_z", ")", "elif", "not", "self", ".", "_m",...
32.625
0.014925
def _walk(self, fd): """Walk and dump (disasm) descriptor. """ top = '.{}'.format(fd.package) if len(fd.package) > 0 else '' for e in fd.enum_type: self._dump_enum(e, top) for m in fd.message_type: self. _dump_message(m, top)
[ "def", "_walk", "(", "self", ",", "fd", ")", ":", "top", "=", "'.{}'", ".", "format", "(", "fd", ".", "package", ")", "if", "len", "(", "fd", ".", "package", ")", ">", "0", "else", "''", "for", "e", "in", "fd", ".", "enum_type", ":", "self", ...
38.285714
0.018248
def bicgstab(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None, callback=None, residuals=None): """Biconjugate Gradient Algorithm with Stabilization. Solves the linear system Ax = b. Left preconditioning is supported. Parameters ---------- A : array, matrix, sparse matrix, Lin...
[ "def", "bicgstab", "(", "A", ",", "b", ",", "x0", "=", "None", ",", "tol", "=", "1e-5", ",", "maxiter", "=", "None", ",", "xtype", "=", "None", ",", "M", "=", "None", ",", "callback", "=", "None", ",", "residuals", "=", "None", ")", ":", "# Con...
29.063694
0.000636
def hex_timestamp_to_datetime(hex_timestamp): """Converts hex timestamp to a datetime object. >>> hex_timestamp_to_datetime('558BBCF9') datetime.datetime(2015, 6, 25, 8, 34, 1) >>> hex_timestamp_to_datetime('0x558BBCF9') datetime.datetime(2015, 6, 25, 8, 34, 1) >>> datetime.fromtimestamp(0x558B...
[ "def", "hex_timestamp_to_datetime", "(", "hex_timestamp", ")", ":", "if", "not", "hex_timestamp", ".", "startswith", "(", "'0x'", ")", ":", "hex_timestamp", "=", "'0x{0}'", ".", "format", "(", "hex_timestamp", ")", "return", "datetime", ".", "fromtimestamp", "("...
37.214286
0.001873
def register_consumer(): """Given a hostname and port attempting to be accessed, return a unique consumer ID for accessing logs from the referenced container.""" global _consumers hostname, port = request.form['hostname'], request.form['port'] app_name = _app_name_from_forwarding_info(hostname,...
[ "def", "register_consumer", "(", ")", ":", "global", "_consumers", "hostname", ",", "port", "=", "request", ".", "form", "[", "'hostname'", "]", ",", "request", ".", "form", "[", "'port'", "]", "app_name", "=", "_app_name_from_forwarding_info", "(", "hostname"...
40.52381
0.001148
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) try: # Create Web Socket connection on block path ws_connection = client(bma.ws.block) # From the documentation ws_connection should be a ClientWebS...
[ "async", "def", "main", "(", ")", ":", "# Create Client from endpoint string in Duniter format", "client", "=", "Client", "(", "BMAS_ENDPOINT", ")", "try", ":", "# Create Web Socket connection on block path", "ws_connection", "=", "client", "(", "bma", ".", "ws", ".", ...
45.042553
0.002312
def init_check_window(self): """ initiates the object that will control steps 1-6 of checking headers, filling in cell values, etc. """ self.check_dia = pmag_er_magic_dialogs.ErMagicCheckFrame3(self, 'Check Data', ...
[ "def", "init_check_window", "(", "self", ")", ":", "self", ".", "check_dia", "=", "pmag_er_magic_dialogs", ".", "ErMagicCheckFrame3", "(", "self", ",", "'Check Data'", ",", "self", ".", "WD", ",", "self", ".", "contribution", ")" ]
48.714286
0.011527
def update_user_password(new_pwd_user_id, new_password,**kwargs): """ Update a user's password """ #check_perm(kwargs.get('user_id'), 'edit_user') try: user_i = db.DBSession.query(User).filter(User.id==new_pwd_user_id).one() user_i.password = bcrypt.hashpw(str(new_password).encod...
[ "def", "update_user_password", "(", "new_pwd_user_id", ",", "new_password", ",", "*", "*", "kwargs", ")", ":", "#check_perm(kwargs.get('user_id'), 'edit_user')", "try", ":", "user_i", "=", "db", ".", "DBSession", ".", "query", "(", "User", ")", ".", "filter", "(...
42.454545
0.014675
def devserver(arguments): """Run a development server.""" import coil.web if coil.web.app: port = int(arguments['--port']) url = 'http://localhost:{0}/'.format(port) coil.web.configure_url(url) coil.web.app.config['DEBUG'] = True if arguments['--browser']: ...
[ "def", "devserver", "(", "arguments", ")", ":", "import", "coil", ".", "web", "if", "coil", ".", "web", ".", "app", ":", "port", "=", "int", "(", "arguments", "[", "'--port'", "]", ")", "url", "=", "'http://localhost:{0}/'", ".", "format", "(", "port",...
30
0.001795
def list_guests(self, host_id, tags=None, cpus=None, memory=None, hostname=None, domain=None, local_disk=None, nic_speed=None, public_ip=None, private_ip=None, **kwargs): """Retrieve a list of all virtual servers on the dedicated host. Example:: # Pr...
[ "def", "list_guests", "(", "self", ",", "host_id", ",", "tags", "=", "None", ",", "cpus", "=", "None", ",", "memory", "=", "None", ",", "hostname", "=", "None", ",", "domain", "=", "None", ",", "local_disk", "=", "None", ",", "nic_speed", "=", "None"...
38.3
0.00198
def getElementByID(self, id): """ returns an element with the specific id and the position of that element within the svg elements array """ pos=0 for element in self._subElements: if element.get_id()==id: return (element,pos) pos+=1
[ "def", "getElementByID", "(", "self", ",", "id", ")", ":", "pos", "=", "0", "for", "element", "in", "self", ".", "_subElements", ":", "if", "element", ".", "get_id", "(", ")", "==", "id", ":", "return", "(", "element", ",", "pos", ")", "pos", "+=",...
37.25
0.022951
def get_tracking_beacon(self, tracking_beacons_id, **data): """ GET /tracking_beacons/:tracking_beacons_id/ Returns the :format:`tracking_beacon` with the specified :tracking_beacons_id. """ return self.get("/tracking_beacons/{0}/".format(tracking_beacons_id), data=data)
[ "def", "get_tracking_beacon", "(", "self", ",", "tracking_beacons_id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "get", "(", "\"/tracking_beacons/{0}/\"", ".", "format", "(", "tracking_beacons_id", ")", ",", "data", "=", "data", ")" ]
44.857143
0.015625
def tokenize(text, custom_dict=None): """ Tokenize given Thai text string Input ===== text: str, Thai text string custom_dict: str (or list), path to customized dictionary file It allows the function not to tokenize given dictionary wrongly. The file should contain custom words ...
[ "def", "tokenize", "(", "text", ",", "custom_dict", "=", "None", ")", ":", "global", "TOKENIZER", "if", "not", "TOKENIZER", ":", "TOKENIZER", "=", "DeepcutTokenizer", "(", ")", "return", "TOKENIZER", ".", "tokenize", "(", "text", ",", "custom_dict", "=", "...
26.730769
0.001389
def create_body(arch:Callable, pretrained:bool=True, cut:Optional[Union[int, Callable]]=None): "Cut off the body of a typically pretrained `model` at `cut` (int) or cut the model as specified by `cut(model)` (function)." model = arch(pretrained) cut = ifnone(cut, cnn_config(arch)['cut']) if cut is None:...
[ "def", "create_body", "(", "arch", ":", "Callable", ",", "pretrained", ":", "bool", "=", "True", ",", "cut", ":", "Optional", "[", "Union", "[", "int", ",", "Callable", "]", "]", "=", "None", ")", ":", "model", "=", "arch", "(", "pretrained", ")", ...
66.3
0.028274
def _get_id2upper(id2upper, item_id, item_obj): """Add the parent item IDs for one item object and their upper.""" if item_id in id2upper: return id2upper[item_id] upper_ids = set() for upper_obj in item_obj.get_goterms_upper(): upper_id = upper_obj.item_id upper_ids.add(upper_id...
[ "def", "_get_id2upper", "(", "id2upper", ",", "item_id", ",", "item_obj", ")", ":", "if", "item_id", "in", "id2upper", ":", "return", "id2upper", "[", "item_id", "]", "upper_ids", "=", "set", "(", ")", "for", "upper_obj", "in", "item_obj", ".", "get_goterm...
39.272727
0.002262
def get_items_by_id(self, jid, node, ids): """ Request specific items by their IDs from a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the PubSub node to query. :type node: :class:`str` :param ids: The item...
[ "def", "get_items_by_id", "(", "self", ",", "jid", ",", "node", ",", "ids", ")", ":", "iq", "=", "aioxmpp", ".", "stanza", ".", "IQ", "(", "to", "=", "jid", ",", "type_", "=", "aioxmpp", ".", "structs", ".", "IQType", ".", "GET", ")", "iq", ".", ...
36.648649
0.001437
async def get(self, source_, *args, **kwargs): """Get the model instance. :param source_: model or base query for lookup Example:: async def my_async_func(): obj1 = await objects.get(MyModel, id=1) obj2 = await objects.get(MyModel, MyModel.id==1) ...
[ "async", "def", "get", "(", "self", ",", "source_", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "connect", "(", ")", "if", "isinstance", "(", "source_", ",", "peewee", ".", "Query", ")", ":", "query", "=", "source_", ...
29.470588
0.001932
def update(self, newinfo): '''update the image''' self.text = newinfo.text if self.textctrl is not None: self.textctrl.Clear() self.textctrl.WriteText(self.text) self._resize()
[ "def", "update", "(", "self", ",", "newinfo", ")", ":", "self", ".", "text", "=", "newinfo", ".", "text", "if", "self", ".", "textctrl", "is", "not", "None", ":", "self", ".", "textctrl", ".", "Clear", "(", ")", "self", ".", "textctrl", ".", "Write...
32.857143
0.008475
def load_from_arpa_str(self, arpa_str): """ Initialize N-gram model by reading an ARPA language model string. Parameters ---------- arpa_str : str A string in ARPA language model file format """ data_found = False end_found = False in_...
[ "def", "load_from_arpa_str", "(", "self", ",", "arpa_str", ")", ":", "data_found", "=", "False", "end_found", "=", "False", "in_ngram_block", "=", "0", "for", "i", ",", "line", "in", "enumerate", "(", "arpa_str", ".", "split", "(", "\"\\n\"", ")", ")", "...
46.048387
0.000686
def reset_default_props(**kwargs): """Reset properties to initial cycle point""" global _DEFAULT_PROPS pcycle = plt.rcParams['axes.prop_cycle'] _DEFAULT_PROPS = { 'color': itertools.cycle(_get_standard_colors(**kwargs)) if len(kwargs) > 0 else itertools.cycle([x['color'] for x in pcycle]...
[ "def", "reset_default_props", "(", "*", "*", "kwargs", ")", ":", "global", "_DEFAULT_PROPS", "pcycle", "=", "plt", ".", "rcParams", "[", "'axes.prop_cycle'", "]", "_DEFAULT_PROPS", "=", "{", "'color'", ":", "itertools", ".", "cycle", "(", "_get_standard_colors",...
44.3
0.002212
def get_2d_markers( self, component_info=None, data=None, component_position=None, index=None ): """Get 2D markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array. """ return self._get_2d_markers...
[ "def", "get_2d_markers", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ",", "index", "=", "None", ")", ":", "return", "self", ".", "_get_2d_markers", "(", "data", ",", "component_info", "...
35.181818
0.010076
def add_bounds_axes(self, *args, **kwargs): """Deprecated""" logging.warning('`add_bounds_axes` is deprecated. Use `show_bounds` or `show_grid`.') return self.show_bounds(*args, **kwargs)
[ "def", "add_bounds_axes", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "warning", "(", "'`add_bounds_axes` is deprecated. Use `show_bounds` or `show_grid`.'", ")", "return", "self", ".", "show_bounds", "(", "*", "args", ",", ...
52
0.014218
def read(cls, data): """Reads data from URL, Dataframe, JSON string, JSON file or OrderedDict. Args: data: can be a Pandas Dataframe, a JSON file, a JSON string, an OrderedDict or a URL pointing to a JSONstat file. Returns: An object of class...
[ "def", "read", "(", "cls", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "return", "cls", "(", "(", "json", ".", "loads", "(", "to_json_stat", "(", "data", ",", "output", "=", "'dict'", ",", "version...
37.088235
0.001546
def _thread_to_xml(self, thread): """ thread information as XML """ name = pydevd_xml.make_valid_xml_value(thread.getName()) cmdText = '<thread name="%s" id="%s" />' % (quote(name), get_thread_id(thread)) return cmdText
[ "def", "_thread_to_xml", "(", "self", ",", "thread", ")", ":", "name", "=", "pydevd_xml", ".", "make_valid_xml_value", "(", "thread", ".", "getName", "(", ")", ")", "cmdText", "=", "'<thread name=\"%s\" id=\"%s\" />'", "%", "(", "quote", "(", "name", ")", ",...
49.4
0.011952
def read(self, timeout=20.0): """ read data on the IN endpoint associated to the HID interface """ start = time() while len(self.rcv_data) == 0: sleep(0) if time() - start > timeout: # Read operations should typically take ~1-2ms. ...
[ "def", "read", "(", "self", ",", "timeout", "=", "20.0", ")", ":", "start", "=", "time", "(", ")", "while", "len", "(", "self", ".", "rcv_data", ")", "==", "0", ":", "sleep", "(", "0", ")", "if", "time", "(", ")", "-", "start", ">", "timeout", ...
46.705882
0.002469
def wns_send_bulk_message( uri_list, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs ): """ WNS doesn't support bulk notification, so we loop through each uri. :param uri_list: list: A list of uris the notification will be sent to. :param message: str: The notification data to be sent. ...
[ "def", "wns_send_bulk_message", "(", "uri_list", ",", "message", "=", "None", ",", "xml_data", "=", "None", ",", "raw_data", "=", "None", ",", "application_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "res", "=", "[", "]", "if", "uri_list", ":"...
33.6
0.028944
def generate_jwt_token(user, authsys, **kwargs): """Generate a new JWT token, with optional extra information. Any data provided in `**kwargs` will be added into the token object for auth specific usage Args: user (:obj:`User`): User object to generate token for authsys (str): The auth syst...
[ "def", "generate_jwt_token", "(", "user", ",", "authsys", ",", "*", "*", "kwargs", ")", ":", "# Local import to prevent app startup failures", "from", "cloud_inquisitor", ".", "config", "import", "dbconfig", "token", "=", "{", "'auth_system'", ":", "authsys", ",", ...
32.807692
0.002278
def is_indexed(self, dataset): """ Returns True if dataset is already indexed. Otherwise returns False. """ with self.index.searcher() as searcher: result = searcher.search(Term('vid', dataset.vid)) return bool(result)
[ "def", "is_indexed", "(", "self", ",", "dataset", ")", ":", "with", "self", ".", "index", ".", "searcher", "(", ")", "as", "searcher", ":", "result", "=", "searcher", ".", "search", "(", "Term", "(", "'vid'", ",", "dataset", ".", "vid", ")", ")", "...
50.8
0.011628
def push(path, keep_symlinks=False, upload_path=None, remove_source=False): ''' WARNING Files pushed to the master will have global read permissions.. Push a file from the minion up to the master, the file will be saved to the salt master in the master's minion files cachedir (defaults to ``/var/ca...
[ "def", "push", "(", "path", ",", "keep_symlinks", "=", "False", ",", "upload_path", "=", "None", ",", "remove_source", "=", "False", ")", ":", "log", ".", "debug", "(", "'Trying to copy \\'%s\\' to master'", ",", "path", ")", "if", "'../'", "in", "path", "...
38.795699
0.001081
def tokenize_text(string): """ Tokenize input text to paragraphs, sentences and words. Tokenization to paragraphs is done using simple Newline algorithm For sentences and words tokenizers above are used :param string: Text to tokenize :type string: str or unicode :return: text, tokenized i...
[ "def", "tokenize_text", "(", "string", ")", ":", "string", "=", "six", ".", "text_type", "(", "string", ")", "rez", "=", "[", "]", "for", "part", "in", "string", ".", "split", "(", "'\\n'", ")", ":", "par", "=", "[", "]", "for", "sent", "in", "to...
30.095238
0.001534
def _store_generic_inference_results(self, results_dict, all_params, all_names): """ Store the model inference values that are common to all choice models. This includes thi...
[ "def", "_store_generic_inference_results", "(", "self", ",", "results_dict", ",", "all_params", ",", "all_names", ")", ":", "# Store the utility coefficients", "self", ".", "_store_inferential_results", "(", "results_dict", "[", "\"utility_coefs\"", "]", ",", "index_names...
48.754545
0.000914
def get(self, id): """ Get a single instance by pk id. :param id: The UUID of the instance you want to retrieve. """ with rconnect() as conn: if id is None: raise ValueError if isinstance(id, uuid.UUID): id = str(...
[ "def", "get", "(", "self", ",", "id", ")", ":", "with", "rconnect", "(", ")", "as", "conn", ":", "if", "id", "is", "None", ":", "raise", "ValueError", "if", "isinstance", "(", "id", ",", "uuid", ".", "UUID", ")", ":", "id", "=", "str", "(", "id...
25.451613
0.002442
def calc_log_likelihood(beta, design, alt_IDs, rows_to_obs, rows_to_alts, choice_vector, utility_transform, intercept_params=None, ...
[ "def", "calc_log_likelihood", "(", "beta", ",", "design", ",", "alt_IDs", ",", "rows_to_obs", ",", "rows_to_alts", ",", "choice_vector", ",", "utility_transform", ",", "intercept_params", "=", "None", ",", "shape_params", "=", "None", ",", "ridge", "=", "None", ...
48.46875
0.000211
def remove(text, exclude): """Remove ``exclude`` symbols from ``text``. Example: >>> remove("example text", string.whitespace) 'exampletext' Args: text (str): The text to modify exclude (iterable): The symbols to exclude Returns: ``text`` with ``exclude`` symbo...
[ "def", "remove", "(", "text", ",", "exclude", ")", ":", "exclude", "=", "''", ".", "join", "(", "str", "(", "symbol", ")", "for", "symbol", "in", "exclude", ")", "return", "text", ".", "translate", "(", "str", ".", "maketrans", "(", "''", ",", "''"...
27.375
0.002208
def _call(self, cmd, get_output): """Calls a command through the SSH connection. Remote stderr gets printed to this program's stderr. Output is captured and may be returned. """ server_err = self.server_logger() chan = self.get_client().get_transport().open_session() ...
[ "def", "_call", "(", "self", ",", "cmd", ",", "get_output", ")", ":", "server_err", "=", "self", ".", "server_logger", "(", ")", "chan", "=", "self", ".", "get_client", "(", ")", ".", "get_transport", "(", ")", ".", "open_session", "(", ")", "try", "...
37.314286
0.001493
def __make_fn(self): """Initialize the mandatory `self.fn` from `self.n`. This is a workaround for buggy clients which set only one of them.""" s=[] if self.n.prefix: s.append(self.n.prefix) if self.n.given: s.append(self.n.given) if self.n.middle...
[ "def", "__make_fn", "(", "self", ")", ":", "s", "=", "[", "]", "if", "self", ".", "n", ".", "prefix", ":", "s", ".", "append", "(", "self", ".", "n", ".", "prefix", ")", "if", "self", ".", "n", ".", "given", ":", "s", ".", "append", "(", "s...
32.529412
0.012302
def plotConvergenceByColumn(results, columnRange, featureRange, numTrials): """ Plots the convergence graph: iterations vs number of columns. Each curve shows the convergence for a given number of unique features. """ ######################################################################## # # Accumulate ...
[ "def", "plotConvergenceByColumn", "(", "results", ",", "columnRange", ",", "featureRange", ",", "numTrials", ")", ":", "########################################################################", "#", "# Accumulate all the results per column in a convergence array.", "#", "# Convergen...
38.065217
0.020601
def bake(self): """ Bake an ``ansible-playbook`` command so it's ready to execute and returns ``None``. :return: None """ # Pass a directory as inventory to let Ansible merge the multiple # inventory sources located under self.add_cli_arg('inventory', ...
[ "def", "bake", "(", "self", ")", ":", "# Pass a directory as inventory to let Ansible merge the multiple", "# inventory sources located under", "self", ".", "add_cli_arg", "(", "'inventory'", ",", "self", ".", "_config", ".", "provisioner", ".", "inventory_directory", ")", ...
36.787879
0.001605
def train(self, data, **kwargs): """ Calculate the standard deviations and means in the training data """ self.data = data for i in xrange(0,data.shape[1]): column_mean = np.mean(data.icol(i)) column_stdev = np.std(data.icol(i)) #Have to do +=...
[ "def", "train", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "self", ".", "data", "=", "data", "for", "i", "in", "xrange", "(", "0", ",", "data", ".", "shape", "[", "1", "]", ")", ":", "column_mean", "=", "np", ".", "mean", "(...
34.642857
0.008032
def com_google_fonts_check_production_encoded_glyphs(ttFont, api_gfonts_ttFont): """Check font has same encoded glyphs as version hosted on fonts.google.com""" cmap = ttFont['cmap'].getcmap(3, 1).cmap gf_cmap = api_gfonts_ttFont['cmap'].getcmap(3, 1).cmap missing_codepoints = set(gf_cmap.keys()) - set(cmap.ke...
[ "def", "com_google_fonts_check_production_encoded_glyphs", "(", "ttFont", ",", "api_gfonts_ttFont", ")", ":", "cmap", "=", "ttFont", "[", "'cmap'", "]", ".", "getcmap", "(", "3", ",", "1", ")", ".", "cmap", "gf_cmap", "=", "api_gfonts_ttFont", "[", "'cmap'", "...
45.666667
0.011445
def apply_features(body, features): '''Applies features to message body lines. Returns list of lists. Each of the lists corresponds to the body line and is constituted by the numbers of features occurrences (0 or 1). E.g. if element j of list i equals 1 this means that feature j occurred in line i ...
[ "def", "apply_features", "(", "body", ",", "features", ")", ":", "# collect all non empty lines", "lines", "=", "[", "line", "for", "line", "in", "body", ".", "splitlines", "(", ")", "if", "line", ".", "strip", "(", ")", "]", "# take the last SIGNATURE_MAX_LIN...
40.352941
0.001425
def flip(self): ''' :returns: None Swaps the positions of A and B. ''' tmp = self.A.xyz self.A = self.B self.B = tmp
[ "def", "flip", "(", "self", ")", ":", "tmp", "=", "self", ".", "A", ".", "xyz", "self", ".", "A", "=", "self", ".", "B", "self", ".", "B", "=", "tmp" ]
18.333333
0.011561
def boxcox(X): """ Gaussianize X using the Box-Cox transformation: [samples x phenotypes] - each phentoype is brought to a positive schale, by first subtracting the minimum value and adding 1. - Then each phenotype transformed by the boxcox transformation """ X_transformed = sp.zeros_like(X) ...
[ "def", "boxcox", "(", "X", ")", ":", "X_transformed", "=", "sp", ".", "zeros_like", "(", "X", ")", "maxlog", "=", "sp", ".", "zeros", "(", "X", ".", "shape", "[", "1", "]", ")", "for", "i", "in", "range", "(", "X", ".", "shape", "[", "1", "]"...
39.2
0.011628
def to_dict(self): """ Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object """ #TODO: Implemen...
[ "def", "to_dict", "(", "self", ")", ":", "#TODO: Implement a more memory efficient variant", "if", "self", ".", "L", "is", "None", ":", "return", "{", "\"mu\"", ":", "self", ".", "mu", ".", "tolist", "(", ")", ",", "\"Sigma\"", ":", "self", ".", "Sigma", ...
39.5
0.012367
def page(self, number, *args, **kwargs): """Return a standard ``Page`` instance with custom, digg-specific page ranges attached. """ page = super().page(number, *args, **kwargs) number = int(number) # we know this will work # easier access num_pages, body, tail,...
[ "def", "page", "(", "self", ",", "number", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "page", "=", "super", "(", ")", ".", "page", "(", "number", ",", "*", "args", ",", "*", "*", "kwargs", ")", "number", "=", "int", "(", "number", "...
46.52
0.001684
def _generate_lambda(self): """ Generate the lambda function and its IAM role, and add to self.tf_conf """ self.tf_conf['resource']['aws_lambda_function']['lambda_func'] = { 'filename': 'webhook2lambda2sqs_func.zip', 'function_name': self.resource_name, ...
[ "def", "_generate_lambda", "(", "self", ")", ":", "self", ".", "tf_conf", "[", "'resource'", "]", "[", "'aws_lambda_function'", "]", "[", "'lambda_func'", "]", "=", "{", "'filename'", ":", "'webhook2lambda2sqs_func.zip'", ",", "'function_name'", ":", "self", "."...
43.944444
0.002475
def concatmap(source, func, *more_sources, task_limit=None): """Apply a given function that creates a sequence from the elements of one or several asynchronous sequences, and generate the elements of the created sequences in order. The function is applied as described in `map`, and must return an a...
[ "def", "concatmap", "(", "source", ",", "func", ",", "*", "more_sources", ",", "task_limit", "=", "None", ")", ":", "return", "concat", ".", "raw", "(", "combine", ".", "smap", ".", "raw", "(", "source", ",", "func", ",", "*", "more_sources", ")", ",...
49.416667
0.001656
def with_upcoming_occurrences(self): """ :return: events having upcoming occurrences, and all their children """ return self.filter( Q(is_drop_in=False, occurrences__start__gte=djtz.now) | Q(Q(is_drop_in=True) | Q(occurrences__is_all_day=True), occurrences__end__g...
[ "def", "with_upcoming_occurrences", "(", "self", ")", ":", "return", "self", ".", "filter", "(", "Q", "(", "is_drop_in", "=", "False", ",", "occurrences__start__gte", "=", "djtz", ".", "now", ")", "|", "Q", "(", "Q", "(", "is_drop_in", "=", "True", ")", ...
41.75
0.008798
def extract_contours(array, tile, interval=100, field='elev', base=0): """ Extract contour lines from an array. Parameters ---------- array : array input elevation data tile : Tile tile covering the array interval : integer elevation value interval when drawing conto...
[ "def", "extract_contours", "(", "array", ",", "tile", ",", "interval", "=", "100", ",", "field", "=", "'elev'", ",", "base", "=", "0", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "levels", "=", "_get_contour_values", "(", "array", ".", ...
30.76
0.00063
def drop(self, codes, level=None, errors='raise'): """ Make new MultiIndex with passed list of codes deleted Parameters ---------- codes : array-like Must be a list of tuples level : int or level name, default None Returns ------- dro...
[ "def", "drop", "(", "self", ",", "codes", ",", "level", "=", "None", ",", "errors", "=", "'raise'", ")", ":", "if", "level", "is", "not", "None", ":", "return", "self", ".", "_drop_from_level", "(", "codes", ",", "level", ")", "try", ":", "if", "no...
35.535714
0.000978