Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def run(host, node, port, endpoint, tls, username, password, keyring, search_from, search_to, mode, output, follow, interval, limit, latency, strea...
[ "\n Bonfire - A graylog CLI client\n " ]
Please provide a description of the function:def seek(self, offset: int = 0, *args, **kwargs): return self.fp.seek(offset, *args, **kwargs)
[ "\n A shortcut to ``self.fp.seek``.\n\n " ]
Please provide a description of the function:def close(self, force=False) -> None: self.fp.close = self._close if self._manual_opened or force: self.fp.close()
[ "\n Closes the file if the file was opened by :class:`File`,\n if not, this does nothing.\n\n Parameters\n ----------\n force: bool\n If set to :class:`True`, force close every file.\n\n " ]
Please provide a description of the function:def set_title(self, title: str, url: str = None) -> None: self.title = title self.url = url
[ "\n Sets the title of the embed.\n\n Parameters\n ----------\n title: str\n Title of the embed.\n\n url: str or None, optional\n URL hyperlink of the title.\n\n " ]
Please provide a description of the function:def set_timestamp(self, time: Union[str, datetime.datetime] = None, now: bool = False) -> None: if now: self.timestamp = str(datetime.datetime.utcnow()) else: self.timestamp = str(time)
[ "\n Sets the timestamp of the embed.\n\n Parameters\n ----------\n time: str or :class:`datetime.datetime`\n The ``ISO 8601`` timestamp from the embed.\n\n now: bool\n Defaults to :class:`False`.\n If set to :class:`True` the current time is used f...
Please provide a description of the function:def add_field(self, name: str, value: str, inline: bool = True) -> None: field = { 'name': name, 'value': value, 'inline': inline } self.fields.append(field)
[ "\n Adds an embed field.\n\n Parameters\n ----------\n name: str\n Name attribute of the embed field.\n\n value: str\n Value attribute of the embed field.\n\n inline: bool\n Defaults to :class:`True`.\n Whether or not the embed sh...
Please provide a description of the function:def set_author(self, name: str, icon_url: str = None, url: str = None) -> \ None: self.author = { 'name': name, 'icon_url': icon_url, 'url': url }
[ "\n Sets the author of the embed.\n\n Parameters\n ----------\n name: str\n The author's name.\n\n icon_url: str, optional\n URL for the author's icon.\n\n url: str, optional\n URL hyperlink for the author.\n\n " ]
Please provide a description of the function:def set_footer(self, text: str, icon_url: str = None) -> None: self.footer = { 'text': text, 'icon_url': icon_url }
[ "\n Sets the footer of the embed.\n\n Parameters\n ----------\n text: str\n The footer text.\n\n icon_url: str, optional\n URL for the icon in the footer.\n\n " ]
Please provide a description of the function:def to_dict(self) -> dict: return { key: getattr(self, key) for key in self.__slots__ if getattr(self, key) is not None }
[ "\n Turns the :class:`Embed` object into a dictionary.\n " ]
Please provide a description of the function:async def init(app, loop): app.session = aiohttp.ClientSession(loop=loop) # to make web requests app.webhook = Webhook.Async(webhook_url, session=app.session) em = Embed(color=0x2ecc71) em.set_author('[INFO] Starting Worker') em.description = 'Host...
[ "Sends a message to the webhook channel when server starts." ]
Please provide a description of the function:async def server_stop(app, loop): em = Embed(color=0xe67e22) em.set_footer('Host: {}'.format(socket.gethostname())) em.description = '[INFO] Server Stopped' await app.webhook.send(embed=em) await app.session.close()
[ "Sends a message to the webhook channel when server stops." ]
Please provide a description of the function:async def message(request): msg = request.get('msg') if msg is None: return request.text("To send a message, go to 0.0.0.0:8000/" "message/?msg='insert message here'.") await app.webhook.send(msg) return response.text...
[ "\n To send a message, go to 0.0.0.0:8000/message/?msg='insert message here'.\n " ]
Please provide a description of the function:def deprecated(*args, **kwargs): if args and isinstance(args[0], string_types): kwargs['reason'] = args[0] args = args[1:] if args and not callable(args[0]): raise TypeError(repr(type(args[0]))) if args: action = kwargs.get(...
[ "\n This is a decorator which can be used to mark functions\n as deprecated. It will result in a warning being emitted\n when the function is used.\n\n **Classic usage:**\n\n To use this, decorate your deprecated function with **@deprecated** decorator:\n\n .. code-block:: python\n\n from de...
Please provide a description of the function:def get_deprecated_msg(self, wrapped, instance): if instance is None: if inspect.isclass(wrapped): fmt = "Call to deprecated class {name}." else: fmt = "Call to deprecated function (or staticmethod) {na...
[ "\n Get the deprecation warning message for the user.\n\n :param wrapped: Wrapped class or function.\n\n :param instance: The object to which the wrapped function was bound when it was called.\n\n :return: The warning message.\n " ]
Please provide a description of the function:def versionadded(reason="", version=""): adapter = SphinxAdapter('versionadded', reason=reason, version=version) # noinspection PyUnusedLocal @wrapt.decorator(adapter=adapter) def wrapper(wrapped, instance, args, kwargs): return wrapped(*args, *...
[ "\n This decorator can be used to insert a \"versionadded\" directive\n in your function/class docstring in order to documents the\n version of the project which adds this new functionality in your library.\n\n :param str reason:\n Reason message which documents the addition in your library (can ...
Please provide a description of the function:def deprecated(*args, **kwargs): directive = kwargs.pop('directive', 'deprecated') adapter_cls = kwargs.pop('adapter_cls', SphinxAdapter) return _classic_deprecated(*args, directive=directive, ada...
[ "\n This decorator can be used to insert a \"deprecated\" directive\n in your function/class docstring in order to documents the\n version of the project which deprecates this functionality in your library.\n\n Keyword arguments can be:\n\n - \"reason\":\n Reason message which documents the ...
Please provide a description of the function:def better_print(self, printer=None): printer = printer or pprint.pprint printer(self.value)
[ "\n Print the value using a *printer*.\n\n :param printer: Callable used to print the value, by default: :func:`pprint.pprint`\n " ]
Please provide a description of the function:def slack_user(request, api_data): if request.user.is_anonymous: return request, api_data data = deepcopy(api_data) slacker, _ = SlackUser.objects.get_or_create(slacker=request.user) slacker.access_token = data.pop('access_token') slacker.e...
[ "\n Pipeline for backward compatibility prior to 1.0.0 version.\n In case if you're willing maintain `slack_user` table.\n\n " ]
Please provide a description of the function:def read(varin, fname='MS2_L10.mat.txt'): '''Read in dataset for variable var :param varin: Variable for which to read in data. ''' # # fname = 'MS09_L10.mat.txt' # # fname = 'MS09_L05.mat.txt' # has PAR # fname = 'MS2_L10.mat.txt' # empty PAR ...
[]
Please provide a description of the function:def show(cmap, var, vmin=None, vmax=None): '''Show a colormap for a chosen input variable var side by side with black and white and jet colormaps. :param cmap: Colormap instance :param var: Variable to plot. :param vmin=None: Min plot value. :param v...
[]
Please provide a description of the function:def plot_data(): '''Plot sample data up with the fancy colormaps. ''' var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM'] # colorbar limits for each property lims = np.array([[26, 33], [0, 10], [0...
[]
Please provide a description of the function:def plot_lightness(saveplot=False): '''Plot lightness of colormaps together. ''' from colorspacious import cspace_converter dc = 1. x = np.linspace(0.0, 1.0, 256) locs = [] # locations for text labels fig = plt.figure(figsize=(16, 5)) ax ...
[]
Please provide a description of the function:def plot_gallery(saveplot=False): '''Make plot of colormaps and labels, like in the matplotlib gallery. :param saveplot=False: Whether to save the plot or not. ''' from colorspacious import cspace_converter gradient = np.linspace(0, 1, 256) gr...
[]
Please provide a description of the function:def wrap_viscm(cmap, dpi=100, saveplot=False): '''Evaluate goodness of colormap using perceptual deltas. :param cmap: Colormap instance. :param dpi=100: dpi for saved image. :param saveplot=False: Whether to save the plot or not. ''' from viscm imp...
[]
Please provide a description of the function:def quick_plot(cmap, fname=None, fig=None, ax=None, N=10): '''Show quick test of a colormap. ''' x = np.linspace(0, 10, N) X, _ = np.meshgrid(x, x) if ax is None: fig = plt.figure() ax = fig.add_subplot(111) mappable = ax.pcolor(X, ...
[]
Please provide a description of the function:def print_colormaps(cmaps, N=256, returnrgb=True, savefiles=False): '''Print colormaps in 256 RGB colors to text files. :param returnrgb=False: Whether or not to return the rgb array. Only makes sense to do if print one colormaps' rgb. ''' rgb = [] fo...
[]
Please provide a description of the function:def get_dict(cmap, N=256): '''Change from rgb to dictionary that LinearSegmentedColormap expects. Code from https://mycarta.wordpress.com/2014/04/25/convert-color-palettes-to-python-matplotlib-colormaps/ and http://nbviewer.ipython.org/github/kwinkunks/notebooks/...
[]
Please provide a description of the function:def cmap(rgbin, N=256): '''Input an array of rgb values to generate a colormap. :param rgbin: An [mx3] array, where m is the number of input color triplets which are interpolated between to make the colormap that is returned. hex values can be inpu...
[]
Please provide a description of the function:def lighten(cmapin, alpha): '''Lighten a colormap by adding alpha < 1. :param cmap: A colormap object, like cmocean.cm.matter. :param alpha: An alpha or transparency value to assign the colormap. Alpha of 1 is opaque and of 1 is fully transparent. O...
[]
Please provide a description of the function:def crop(cmapin, vmin, vmax, pivot, N=None, dmax=None): '''Crop end or ends of a diverging colormap by vmin/vmax values. :param cmap: A colormap object, like cmocean.cm.matter. :param vmin/vmax: vmin/vmax for use in plot with colormap. :param pivot: center p...
[]
Please provide a description of the function:def crop_by_percent(cmap, per, which='both', N=None): '''Crop end or ends of a colormap by per percent. :param cmap: A colormap object, like cmocean.cm.matter. :param per: Percent of colormap to remove. If which=='both', take this percent off both ends o...
[]
Please provide a description of the function:def _api(fn): @_functools.wraps(fn) def _fn(self, *args, **kwargs): self._throttle_wait() if not self._SID: raise RuntimeError('Session closed. Invoke connect() before.') return fn(self, *args, **kw...
[ "API decorator for common tests (sessions open, etc.) and throttle\n limitation (calls per second)." ]
Please provide a description of the function:def _premium(fn): @_functools.wraps(fn) def _fn(self, *args, **kwargs): if self._lite: raise RuntimeError('Premium API not available in lite access.') return fn(self, *args, **kwargs) return _fn
[ "Premium decorator for APIs that require premium access level." ]
Please provide a description of the function:def make_retrieveParameters(offset=1, count=100, name='RS', sort='D'): return _OrderedDict([ ('firstRecord', offset), ('count', count), ('sortField', _OrderedDict([('name', name), ('sort', sort)])) ])
[ "Create retrieve parameters dictionary to be used with APIs.\n\n :count: Number of records to display in the result. Cannot be less than\n 0 and cannot be greater than 100. If count is 0 then only the\n summary information will be returned.\n\n :offset: First record in re...
Please provide a description of the function:def connect(self): if not self._SID: self._SID = self._auth.service.authenticate() print('Authenticated (SID: %s)' % self._SID) self._search.set_options(headers={'Cookie': 'SID="%s"' % self._SID}) self._auth.options.h...
[ "Authenticate to WOS and set the SID cookie." ]
Please provide a description of the function:def close(self): if self._SID: self._auth.service.closeSession() self._SID = None
[ "The close operation loads the session if it is valid and then closes\n it and releases the session seat. All the session data are deleted and\n become invalid after the request is processed. The session ID can no\n longer be used in subsequent requests." ]
Please provide a description of the function:def search(self, query, count=5, offset=1, editions=None, symbolicTimeSpan=None, timeSpan=None, retrieveParameters=None): return self._search.service.search( queryParameters=_OrderedDict([ ('databaseId', 'WOS'), ...
[ "The search operation submits a search query to the specified\n database edition and retrieves data. This operation returns a query ID\n that can be used in subsequent operations to retrieve more records.\n\n :query: User query for requesting data. The query parser will return\n ...
Please provide a description of the function:def citedReferences(self, uid, count=100, offset=1, retrieveParameters=None): return self._search.service.citedReferences( databaseId='WOS', uid=uid, queryLanguage='en', retrieveParamete...
[ "The citedReferences operation returns references cited by an article\n identified by a unique identifier. You may specify only one identifier\n per request.\n\n :uid: Thomson Reuters unique record identifier\n\n :count: Number of records to display in the result. Cannot be less than\n ...
Please provide a description of the function:def citedReferencesRetrieve(self, queryId, count=100, offset=1, retrieveParameters=None): return self._search.service.citedReferencesRetrieve( queryId=queryId, retrieveParameters=(retrieveParameters or ...
[ "The citedReferencesRetrieve operation submits a query returned by a\n previous citedReferences operation.\n\n This operation is useful for overcoming the retrieval limit of 100\n records per query. For example, a citedReferences operation may find\n 106 cited references, as revealed by ...
Please provide a description of the function:def citingArticles(self, uid, count=100, offset=1, editions=None, timeSpan=None, retrieveParameters=None): return self._search.service.citingArticles( databaseId='WOS', uid=uid, editions=editions, ...
[ "The citingArticles operation finds citing articles for the article\n specified by unique identifier. You may specify only one identifier per\n request. Web of Science Core Collection (WOS) is the only valid\n database for this operation.\n\n :uid: A unique item identifier. It cannot be ...
Please provide a description of the function:def single(wosclient, wos_query, xml_query=None, count=5, offset=1): result = wosclient.search(wos_query, count, offset) xml = _re.sub(' xmlns="[^"]+"', '', result.records, count=1).encode('utf-8') if xml_query: xml = _ET.fromstring(xml) retu...
[ "Perform a single Web of Science query and then XML query the results." ]
Please provide a description of the function:def query(wosclient, wos_query, xml_query=None, count=5, offset=1, limit=100): results = [single(wosclient, wos_query, xml_query, min(limit, count-x+1), x) for x in range(offset, count+1, limit)] if xml_query: return [el for res in results...
[ "Query Web of Science and XML query results with multiple requests." ]
Please provide a description of the function:def doi_to_wos(wosclient, doi): results = query(wosclient, 'DO="%s"' % doi, './REC/UID', count=1) return results[0].lstrip('WOS:') if results else None
[ "Convert DOI to WOS identifier." ]
Please provide a description of the function:def sql_fingerprint(query, hide_columns=True): parsed_query = parse(query)[0] sql_recursively_simplify(parsed_query, hide_columns=hide_columns) return str(parsed_query)
[ "\n Simplify a query, taking away exact values and fields selected.\n\n Imperfect but better than super explicit, value-dependent queries.\n " ]
Please provide a description of the function:def match_keyword(token, keywords): if not token: return False if not token.is_keyword: return False return token.value.upper() in keywords
[ "\n Checks if the given token represents one of the given keywords\n " ]
Please provide a description of the function:def _is_group(token): is_group = token.is_group if isinstance(is_group, bool): return is_group else: return is_group()
[ "\n sqlparse 0.2.2 changed it from a callable to a bool property\n " ]
Please provide a description of the function:def clean_key(cls, key): for var_re in cls.VARIABLE_RES: key = var_re.sub('#', key) return key
[ "\n Replace things that look like variables with a '#' so tests aren't affected by random variables\n " ]
Please provide a description of the function:def sorted_names(names): names = list(names) have_default = False if 'default' in names: names.remove('default') have_default = True sorted_names = sorted(names) if have_default: sorted_names = ['default'] + sorted_names ...
[ "\n Sort a list of names but keep the word 'default' first if it's there.\n " ]
Please provide a description of the function:def record_diff(old, new): return '\n'.join(difflib.ndiff( ['%s: %s' % (k, v) for op in old for k, v in op.items()], ['%s: %s' % (k, v) for op in new for k, v in op.items()], ))
[ "\n Generate a human-readable diff of two performance records.\n " ]
Please provide a description of the function:def dequeue(self, block=True): return self.queue.get(block, self.queue_get_timeout)
[ "Dequeue a record and return item." ]
Please provide a description of the function:def start(self): self._thread = t = threading.Thread(target=self._monitor) t.setDaemon(True) t.start()
[ "Start the listener.\n\n This starts up a background thread to monitor the queue for\n items to process.\n " ]
Please provide a description of the function:def handle(self, record): record = self.prepare(record) for handler in self.handlers: handler(record)
[ "Handle an item.\n\n This just loops through the handlers offering them the record\n to handle.\n " ]
Please provide a description of the function:def _monitor(self): err_msg = ("invalid internal state:" " _stop_nowait can not be set if _stop is not set") assert self._stop.isSet() or not self._stop_nowait.isSet(), err_msg q = self.queue has_task_done = hasatt...
[ "Monitor the queue for items, and ask the handler to deal with them.\n\n This method runs on a separate, internal thread.\n The thread will terminate if it sees a sentinel object in the queue.\n " ]
Please provide a description of the function:def stop(self, nowait=False): self._stop.set() if nowait: self._stop_nowait.set() self.queue.put_nowait(self._sentinel_item) if (self._thread.isAlive() and self._thread is not threading.currentThread()): ...
[ "Stop the listener.\n\n This asks the thread to terminate, and then waits for it to do so.\n Note that if you don't call this before your application exits, there\n may be some records still left on the queue, which won't be processed.\n If nowait is False then thread will handle remaini...
Please provide a description of the function:def terminate(self, nowait=False): logger.debug("Acquiring lock for service termination") with self.lock: logger.debug("Terminating service") if not self.listener: logger.warning("Service already stopped.") ...
[ "Finalize and stop service\n\n Args:\n nowait: set to True to terminate immediately and skip processing\n messages still in the queue\n " ]
Please provide a description of the function:def process_log(self, **log_item): logger.debug("Processing log item: %s", log_item) self.log_batch.append(log_item) if len(self.log_batch) >= self.log_batch_size: self._post_log_batch()
[ "Special handler for log messages.\n\n Accumulate incoming log messages and post them in batch.\n " ]
Please provide a description of the function:def process_item(self, item): logger.debug("Processing item: %s (queue size: %s)", item, self.queue.qsize()) method, kwargs = item if method not in self.supported_methods: raise Error("Not expected service me...
[ "Main item handler.\n\n Called by queue listener.\n " ]
Please provide a description of the function:def log(self, time, message, level=None, attachment=None): logger.debug("log queued") args = { "time": time, "message": message, "level": level, "attachment": attachment, } self.queue.p...
[ "Logs a message with attachment.\n\n The attachment is a dict of:\n name: name of attachment\n data: file content\n mime: content type for attachment\n " ]
Please provide a description of the function:def log_batch(self, log_data): url = uri_join(self.base_url, "log") attachments = [] for log_item in log_data: log_item["item_id"] = self.stack[-1] attachment = log_item.get("attachment", None) if "attac...
[ "Logs batch of messages with attachment.\n\n Args:\n log_data: list of log records.\n log record is a dict of;\n time, message, level, attachment\n attachment is a dict of:\n name: name of attachment\n data: fileobj or ...
Please provide a description of the function:def git_versions_from_keywords(keywords, tag_prefix, verbose): if not keywords: raise NotThisMethod("no keywords at all, weird") date = keywords.get("date") if date is not None: # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant...
[ "Get version information from git keywords." ]
Please provide a description of the function:def render_pep440_branch_based(pieces): replacements = ([' ', '.'], ['(', ''], [')', ''], ['\\', '.'], ['/', '.']) branch_name = pieces.get('branch') or '' if branch_name: for old, new in replacements: branch_name = branch_name.replace(ol...
[ "Build up version string, with post-release \"local version identifier\".\n\n Our goal: TAG[+DISTANCE.BRANCH_gHEX[.dirty]] . Note that if you\n get a tagged build and then dirty it, you'll get TAG+0.BRANCH_gHEX.dirty\n\n Exceptions:\n 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.BRANCH_gHE...
Please provide a description of the function:def render(pieces, style): if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or st...
[ "Render the given version pieces into the requested style." ]
Please provide a description of the function:def do_setup(): root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): ...
[ "Do main VCS-independent setup function for installing Versioneer." ]
Please provide a description of the function:def scan_setup_py(): found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass(" in...
[ "Validate the contents of setup.py against Versioneer's expectations." ]
Please provide a description of the function:def read(fname): ''' Read a file from the directory where setup.py resides ''' file_path = os.path.join(SETUP_DIRNAME, fname) with codecs.open(file_path, encoding='utf-8') as rfh: return rfh.read()
[]
Please provide a description of the function:def fit(self, X, y, X_val=None, y_val=None): y = y.reshape((len(y), 1)) if sparse.issparse(X): X = X.tocsr() if X_val is not None: n_val = len(y_val) y_val = y_val.reshape((n_val, 1)) # Set initi...
[ "Train a network with the quasi-Newton method.\n \n Args:\n X (np.array of float): feature matrix for training\n y (np.array of float): target values for training\n X_val (np.array of float): feature matrix for validation\n y_val (np.array of float): target ...
Please provide a description of the function:def predict(self, X): logger.info('predicting ...') ps = self.predict_raw(X) return sigm(ps[:, 0])
[ "Predict targets for a feature matrix.\n\n Args:\n X (np.array of float): feature matrix for prediction\n\n Returns:\n prediction (np.array)\n " ]
Please provide a description of the function:def predict_raw(self, X): # b -- bias for the input and h layers b = np.ones((X.shape[0], 1)) w2 = self.w[-(self.h + 1):].reshape(self.h + 1, 1) w1 = self.w[:-(self.h + 1)].reshape(self.i + 1, self.h) # Make X to have the sam...
[ "Predict targets for a feature matrix.\n\n Args:\n X (np.array of float): feature matrix for prediction\n " ]
Please provide a description of the function:def func(self, w, *args): x0 = args[0] x1 = args[1] n0 = x0.shape[0] n1 = x1.shape[0] # n -- number of pairs to evaluate n = max(n0, n1) * 10 idx0 = np.random.choice(range(n0), size=n) idx1 = np.rando...
[ "Return the costs of the neural network for predictions.\n\n Args:\n w (array of float): weight vectors such that:\n w[:-h1] -- weights between the input and h layers\n w[-h1:] -- weights between the h and output layers\n args: features (args[0]) and target...
Please provide a description of the function:def fprime(self, w, *args): x0 = args[0] x1 = args[1] n0 = x0.shape[0] n1 = x1.shape[0] # n -- number of pairs to evaluate n = max(n0, n1) * 10 idx0 = np.random.choice(range(n0), size=n) idx1 = np.ra...
[ "Return the derivatives of the cost function for predictions.\n\n Args:\n w (array of float): weight vectors such that:\n w[:-h1] -- weights between the input and h layers\n w[-h1:] -- weights between the h and output layers\n args: features (args[0]) and t...
Please provide a description of the function:def transform(self, X): for col in range(X.shape[1]): X[:, col] = self._transform_col(X[:, col], col) return X
[ "Normalize numerical columns.\n\n Args:\n X (numpy.array) : numerical columns to normalize\n\n Returns:\n X (numpy.array): normalized numerical columns\n " ]
Please provide a description of the function:def fit_transform(self, X, y=None): self.ecdfs = [None] * X.shape[1] for col in range(X.shape[1]): self.ecdfs[col] = ECDF(X[:, col]) X[:, col] = self._transform_col(X[:, col], col) return X
[ "Normalize numerical columns.\n\n Args:\n X (numpy.array) : numerical columns to normalize\n\n Returns:\n X (numpy.array): normalized numerical columns\n " ]
Please provide a description of the function:def _transform_col(self, x, col): return norm.ppf(self.ecdfs[col](x) * .998 + .001)
[ "Normalize one numerical column.\n\n Args:\n x (numpy.array): a numerical column to normalize\n col (int): column index\n\n Returns:\n A normalized feature vector.\n " ]
Please provide a description of the function:def _get_label_encoder_and_max(self, x): # NaN cannot be used as a key for dict. So replace it with a random integer. label_count = x.fillna(NAN_INT).value_counts() n_uniq = label_count.shape[0] label_count = label_count[label_count...
[ "Return a mapping from values and its maximum of a column to integer labels.\n\n Args:\n x (pandas.Series): a categorical column to encode.\n\n Returns:\n label_encoder (dict): mapping from values of features to integers\n max_label (int): maximum label\n " ]
Please provide a description of the function:def _transform_col(self, x, i): return x.fillna(NAN_INT).map(self.label_encoders[i]).fillna(0)
[ "Encode one categorical column into labels.\n\n Args:\n x (pandas.Series): a categorical column to encode\n i (int): column index\n\n Returns:\n x (pandas.Series): a column with labels.\n " ]
Please provide a description of the function:def transform(self, X): for i, col in enumerate(X.columns): X.loc[:, col] = self._transform_col(X[col], i) return X
[ "Encode categorical columns into label encoded columns\n\n Args:\n X (pandas.DataFrame): categorical columns to encode\n\n Returns:\n X (pandas.DataFrame): label encoded columns\n " ]
Please provide a description of the function:def fit_transform(self, X, y=None): self.label_encoders = [None] * X.shape[1] self.label_maxes = [None] * X.shape[1] for i, col in enumerate(X.columns): self.label_encoders[i], self.label_maxes[i] = \ self._get_l...
[ "Encode categorical columns into label encoded columns\n\n Args:\n X (pandas.DataFrame): categorical columns to encode\n\n Returns:\n X (pandas.DataFrame): label encoded columns\n " ]
Please provide a description of the function:def _transform_col(self, x, i): labels = self.label_encoder._transform_col(x, i) label_max = self.label_encoder.label_maxes[i] # build row and column index for non-zero values of a sparse matrix index = np.array(range(len(labels))) ...
[ "Encode one categorical column into sparse matrix with one-hot-encoding.\n\n Args:\n x (pandas.Series): a categorical column to encode\n i (int): column index\n\n Returns:\n X (scipy.sparse.coo_matrix): sparse matrix encoding a categorical\n ...
Please provide a description of the function:def transform(self, X): for i, col in enumerate(X.columns): X_col = self._transform_col(X[col], i) if X_col is not None: if i == 0: X_new = X_col else: X_new = s...
[ "Encode categorical columns into sparse matrix with one-hot-encoding.\n\n Args:\n X (pandas.DataFrame): categorical columns to encode\n\n Returns:\n X_new (scipy.sparse.coo_matrix): sparse matrix encoding categorical\n variables into du...
Please provide a description of the function:def _get_target_encoder(self, x, y): assert len(x) == len(y) # NaN cannot be used as a key for dict. So replace it with a random integer df = pd.DataFrame({y.name: y, x.name: x.fillna(NAN_INT)}) return df.groupby(x.name)[y.name].mea...
[ "Return a mapping from categories to average target values.\n Args:\n x (pandas.Series): a categorical column to encode.\n y (pandas.Series): the target column\n Returns:\n target_encoder (dict): mapping from categories to average target values\n " ]
Please provide a description of the function:def _transform_col(self, x, i): return x.fillna(NAN_INT).map(self.target_encoders[i]).fillna(self.target_mean)
[ "Encode one categorical column into average target values.\n Args:\n x (pandas.Series): a categorical column to encode\n i (int): column index\n Returns:\n x (pandas.Series): a column with labels.\n " ]
Please provide a description of the function:def fit(self, X, y): self.target_encoders = [None] * X.shape[1] self.target_mean = y.mean() for i, col in enumerate(X.columns): self.target_encoders[i] = self._get_target_encoder(X[col], y) return self
[ "Encode categorical columns into average target values.\n Args:\n X (pandas.DataFrame): categorical columns to encode\n y (pandas.Series): the target column\n Returns:\n X (pandas.DataFrame): encoded columns\n " ]
Please provide a description of the function:def fit_transform(self, X, y): self.target_encoders = [None] * X.shape[1] self.target_mean = y.mean() for i, col in enumerate(X.columns): self.target_encoders[i] = self._get_target_encoder(X[col], y) X.loc[:, col] = ...
[ "Encode categorical columns into average target values.\n Args:\n X (pandas.DataFrame): categorical columns to encode\n y (pandas.Series): the target column\n Returns:\n X (pandas.DataFrame): encoded columns\n " ]
Please provide a description of the function:def _calculate_split_score(self, split): left_error = gini(split['left']) right_error = gini(split['right']) error = gini(self.Y) # if the split is any good, the score should be greater than 0 total = float(len(self.Y)) ...
[ "\n calculate the score of the split:\n score = current_error - after_split_error\n " ]
Please provide a description of the function:def predict(self, x): if self._is_leaf(): d1 = self.predict_initialize['count_dict'] d2 = count_dict(self.Y) for key, value in d1.iteritems(): if key in d2: d2[key] += value ...
[ "\n Make prediction recursively. Use both the samples inside the current\n node and the statistics inherited from parent.\n " ]
Please provide a description of the function:def netflix(es, ps, e0, l=.0001): m = len(es) n = len(ps[0]) X = np.stack(ps).T pTy = .5 * (n * e0**2 + (X**2).sum(axis=0) - n * np.array(es)**2) w = np.linalg.pinv(X.T.dot(X) + l * n * np.eye(m)).dot(pTy) return X.dot(w), w
[ "\n Combine predictions with the optimal weights to minimize RMSE.\n\n Args:\n es (list of float): RMSEs of predictions\n ps (list of np.array): predictions\n e0 (float): RMSE of all zero prediction\n l (float): lambda as in the ridge regression\n\n Returns:\n Ensemble pr...
Please provide a description of the function:def save_data(X, y, path): catalog = {'.csv': save_csv, '.sps': save_libsvm, '.h5': save_hdf5} ext = os.path.splitext(path)[1] func = catalog[ext] if y is None: y = np.zeros((X.shape[0], )) func(X, y, path)
[ "Save data as a CSV, LibSVM or HDF5 file based on the file extension.\n\n Args:\n X (numpy or scipy sparse matrix): Data matrix\n y (numpy array): Target vector. If None, all zero vector will be saved.\n path (str): Path to the CSV, LibSVM or HDF5 file to save data.\n " ]
Please provide a description of the function:def save_csv(X, y, path): if sparse.issparse(X): X = X.todense() np.savetxt(path, np.hstack((y.reshape((-1, 1)), X)), delimiter=',')
[ "Save data as a CSV file.\n\n Args:\n X (numpy or scipy sparse matrix): Data matrix\n y (numpy array): Target vector.\n path (str): Path to the CSV file to save data.\n " ]
Please provide a description of the function:def save_libsvm(X, y, path): dump_svmlight_file(X, y, path, zero_based=False)
[ "Save data as a LibSVM file.\n\n Args:\n X (numpy or scipy sparse matrix): Data matrix\n y (numpy array): Target vector.\n path (str): Path to the CSV file to save data.\n " ]
Please provide a description of the function:def save_hdf5(X, y, path): with h5py.File(path, 'w') as f: is_sparse = 1 if sparse.issparse(X) else 0 f['issparse'] = is_sparse f['target'] = y if is_sparse: if not sparse.isspmatrix_csr(X): X = X.tocsr()...
[ "Save data as a HDF5 file.\n\n Args:\n X (numpy or scipy sparse matrix): Data matrix\n y (numpy array): Target vector.\n path (str): Path to the HDF5 file to save data.\n " ]
Please provide a description of the function:def load_data(path, dense=False): catalog = {'.csv': load_csv, '.sps': load_svmlight_file, '.h5': load_hdf5} ext = os.path.splitext(path)[1] func = catalog[ext] X, y = func(path) if dense and sparse.issparse(X): X = X.todense() return...
[ "Load data from a CSV, LibSVM or HDF5 file based on the file extension.\n\n Args:\n path (str): A path to the CSV, LibSVM or HDF5 format file containing data.\n dense (boolean): An optional variable indicating if the return matrix\n should be dense. By default, it is false....
Please provide a description of the function:def load_csv(path): with open(path) as f: line = f.readline().strip() X = np.loadtxt(path, delimiter=',', skiprows=0 if is_number(line.split(',')[0]) else 1) y = np.array(X[:, 0]).flatten() X = X[:, 1:] return X, y
[ "Load data from a CSV file.\n\n Args:\n path (str): A path to the CSV format file containing data.\n dense (boolean): An optional variable indicating if the return matrix\n should be dense. By default, it is false.\n\n Returns:\n Data matrix X and target vector y\...
Please provide a description of the function:def load_hdf5(path): with h5py.File(path, 'r') as f: is_sparse = f['issparse'][...] if is_sparse: shape = tuple(f['shape'][...]) data = f['data'][...] indices = f['indices'][...] indptr = f['indptr'][....
[ "Load data from a HDF5 file.\n\n Args:\n path (str): A path to the HDF5 format file containing data.\n dense (boolean): An optional variable indicating if the return matrix\n should be dense. By default, it is false.\n\n Returns:\n Data matrix X and target vector ...
Please provide a description of the function:def read_sps(path): for line in open(path): # parse x xs = line.rstrip().split(' ') yield xs[1:], int(xs[0])
[ "Read a LibSVM file line-by-line.\n\n Args:\n path (str): A path to the LibSVM file to read.\n\n Yields:\n data (list) and target (int).\n " ]
Please provide a description of the function:def mape(y, p): filt = np.abs(y) > EPS return np.mean(np.abs(1 - p[filt] / y[filt]))
[ "Mean Absolute Percentage Error (MAPE).\n\n Args:\n y (numpy.array): target\n p (numpy.array): prediction\n\n Returns:\n e (numpy.float64): MAPE\n " ]
Please provide a description of the function:def rmse(y, p): # check and get number of samples assert y.shape == p.shape return np.sqrt(mse(y, p))
[ "Root Mean Squared Error (RMSE).\n\n Args:\n y (numpy.array): target\n p (numpy.array): prediction\n\n Returns:\n e (numpy.float64): RMSE\n " ]
Please provide a description of the function:def gini(y, p): # check and get number of samples assert y.shape == p.shape n_samples = y.shape[0] # sort rows on prediction column # (from largest to smallest) arr = np.array([y, p]).transpose() true_order = arr[arr[:,0].argsort()][::-1,0...
[ "Normalized Gini Coefficient.\n\n Args:\n y (numpy.array): target\n p (numpy.array): prediction\n\n Returns:\n e (numpy.float64): normalized Gini coefficient\n " ]
Please provide a description of the function:def logloss(y, p): p[p < EPS] = EPS p[p > 1 - EPS] = 1 - EPS return log_loss(y, p)
[ "Bounded log loss error.\n\n Args:\n y (numpy.array): target\n p (numpy.array): prediction\n\n Returns:\n bounded log loss error\n " ]
Please provide a description of the function:def convert(input_file_name, **kwargs): delimiter = kwargs["delimiter"] or "," quotechar = kwargs["quotechar"] or "|" if six.PY2: delimiter = delimiter.encode("utf-8") quotechar = quotechar.encode("utf-8") # Read CSV and form a header a...
[ "Convert CSV file to HTML table" ]
Please provide a description of the function:def save(file_name, content): with open(file_name, "w", encoding="utf-8") as output_file: output_file.write(content) return output_file.name
[ "Save content to a file" ]