Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def _encode(cls, lits, weights=None, bound=1, top_id=None, encoding=EncType.best, comparator='<'): if encoding < 0 or encoding > 5: raise(NoSuchEncodingError(encoding)) assert lits, 'No literals are provided.' # pre...
[ "\n This is the method that wraps the encoder of PyPBLib. Although the\n method can be invoked directly, a user is expected to call one of\n the following methods instead: :meth:`atmost`, :meth:`atleast`, or\n :meth:`equals`.\n\n The list of literals can contai...
Please provide a description of the function:def leq(cls, lits, weights=None, bound=1, top_id=None, encoding=EncType.best): return cls._encode(lits, weights, bound, top_id, encoding, comparator='<')
[ "\n This method can be used for creating a CNF encoding of a LEQ\n (weighted AtMostK) constraint, i.e. of\n :math:`\\sum_{i=1}^{n}{a_i\\cdot x_i}\\leq k`. The resulting set of\n clauses is returned as an object of class :class:`.formula.CNF`.\n\n The input list...
Please provide a description of the function:def atmost(cls, lits, weights=None, bound=1, top_id=None, encoding=EncType.best): return cls.leq(lits, weights, bound, top_id, encoding)
[ "\n A synonim for :meth:`PBEnc.leq`.\n " ]
Please provide a description of the function:def atleast(cls, lits, weights=None, bound=1, top_id=None, encoding=EncType.best): return cls.geq(lits, weights, bound, top_id, encoding)
[ "\n A synonym for :meth:`PBEnc.geq`.\n " ]
Please provide a description of the function:def parse_options(): try: opts, args = getopt.getopt(sys.argv[1:], 'hms:v', ['help', 'model', 'solver=', 'verbose']) except getopt.GetoptError as err: sys.stderr.write(str(err).capitalize()) print_usage() sys.exit(1) solver ...
[ "\n Parses command-line options.\n " ]
Please provide a description of the function:def print_usage(): print('Usage: ' + os.path.basename(sys.argv[0]) + ' [options] dimacs-file') print('Options:') print(' -h, --help Show this message') print(' -m, --model Print model') print(' -s, --solver SAT so...
[ "\n Prints usage message.\n " ]
Please provide a description of the function:def parse_formula(fml_file): if re.search('\.wcnf(\.(gz|bz2|lzma|xz))?$', fml_file): fml = WCNF(from_file=fml_file) else: # expecting '*.cnf' fml = CNF(from_file=fml_file).weighted() return fml
[ "\n Parse and return MaxSAT formula.\n " ]
Please provide a description of the function:def _init(self, formula): self.oracle = Solver(name=self.solver, bootstrap_with=formula.hard, incr=True, use_timer=True) for i, cl in enumerate(formula.soft): # TODO: if clause is unit, use its literal as selector ...
[ "\n SAT oracle initialization. The method creates a new SAT oracle and\n feeds it with the formula's hard clauses. Afterwards, all soft\n clauses of the formula are augmented with selector literals and\n also added to the solver. The list of all introduced selectors is\n ...
Please provide a description of the function:def delete(self): if self.oracle: self.oracle.delete() self.oracle = None if self.tot: self.tot.delete() self.tot = None
[ "\n Explicit destructor of the internal SAT oracle and the\n :class:`.ITotalizer` object.\n " ]
Please provide a description of the function:def solve(self): is_sat = False while self.oracle.solve(): is_sat = True self.model = self.oracle.get_model() self.cost = self._get_model_cost(self.formula, self.model) if self.verbose: ...
[ "\n Computes a solution to the MaxSAT problem. The method implements\n the LSU/LSUS algorithm, i.e. it represents a loop, each iteration\n of which calls a SAT oracle on the working MaxSAT formula and\n refines the upper bound on the MaxSAT cost until the formula\n ...
Please provide a description of the function:def _get_model_cost(self, formula, model): model_set = set(model) cost = 0 for i, cl in enumerate(formula.soft): cost += formula.wght[i] if all(l not in model_set for l in filter(lambda l: abs(l) <= self.formula.nv, cl)) else 0 ...
[ "\n Given a WCNF formula and a model, the method computes the MaxSAT\n cost of the model, i.e. the sum of weights of soft clauses that are\n unsatisfied by the model.\n\n :param formula: an input MaxSAT formula\n :param model: a satisfying assignment\n\n ...
Please provide a description of the function:def _assert_lt(self, cost): if self.tot == None: self.tot = ITotalizer(lits=self.sels, ubound=cost-1, top_id=self.topv) self.topv = self.tot.top_id for cl in self.tot.cnf.clauses: self.oracle.add_clause(c...
[ "\n The method enforces an upper bound on the cost of the MaxSAT\n solution. This is done by encoding the sum of all soft clause\n selectors with the use the iterative totalizer encoding, i.e.\n :class:`.ITotalizer`. Note that the sum is created once, at the\n ...
Please provide a description of the function:def usage(): print('Usage:', os.path.basename(sys.argv[0]), '[options] dimacs-file') print('Options:') print(' -a, --adapt Try to adapt (simplify) input formula') print(' -c, --comp=<string> Enable one of the MSE18 config...
[ "\n Prints usage message.\n " ]
Please provide a description of the function:def init(self, formula, incr=False): # creating a solver object self.oracle = Solver(name=self.solver, bootstrap_with=formula.hard, incr=incr, use_timer=True) # adding soft clauses to oracle for i, cl in enumerate(fo...
[ "\n Initialize the internal SAT oracle. The oracle is used\n incrementally and so it is initialized only once when\n constructing an object of class :class:`RC2`. Given an\n input :class:`.WCNF` formula, the method bootstraps the\n oracle with its hard clauses....
Please provide a description of the function:def add_clause(self, clause, weight=None): # first, map external literals to internal literals # introduce new variables if necessary cl = list(map(lambda l: self._map_extlit(l), clause)) if not weight: # the clause is h...
[ "\n The method for adding a new hard of soft clause to the\n problem formula. Although the input formula is to be\n specified as an argument of the constructor of\n :class:`RC2`, adding clauses may be helpful when\n *enumerating* MaxSAT solutions of the formula...
Please provide a description of the function:def delete(self): if self.oracle: self.oracle.delete() self.oracle = None if self.solver != 'mc': # for minicard, there is nothing to free for t in six.itervalues(self.tobj): t.delete...
[ "\n Explicit destructor of the internal SAT oracle and all the\n totalizer objects creating during the solving process.\n " ]
Please provide a description of the function:def compute(self): # simply apply MaxSAT only once res = self.compute_() if res: # extracting a model self.model = self.oracle.get_model() self.model = filter(lambda l: abs(l) in self.vmap.i2e, self.model...
[ "\n This method can be used for computing one MaxSAT solution,\n i.e. for computing an assignment satisfying all hard\n clauses of the input formula and maximizing the sum of\n weights of satisfied soft clauses. It is a wrapper for the\n internal :func:`compute...
Please provide a description of the function:def enumerate(self): done = False while not done: model = self.compute() if model != None: self.add_clause([-l for l in model]) yield model else: done = True
[ "\n Enumerate top MaxSAT solutions (from best to worst). The\n method works as a generator, which iteratively calls\n :meth:`compute` to compute a MaxSAT model, blocks it\n internally and returns it.\n\n :returns: a MaxSAT model\n :rtype: list(int)\n...
Please provide a description of the function:def compute_(self): # trying to adapt (simplify) the formula # by detecting and using atmost1 constraints if self.adapt: self.adapt_am1() # main solving loop while not self.oracle.solve(assumptions=self.sels + se...
[ "\n Main core-guided loop, which iteratively calls a SAT\n oracle, extracts a new unsatisfiable core and processes\n it. The loop finishes as soon as a satisfiable formula is\n obtained. If specified in the command line, the method\n additionally calls :meth:`a...
Please provide a description of the function:def get_core(self): # extracting the core self.core = self.oracle.get_core() if self.core: # try to reduce the core by trimming self.trim_core() # and by heuristic minimization self.minimize_...
[ "\n Extract unsatisfiable core. The result of the procedure is\n stored in variable ``self.core``. If necessary, core\n trimming and also heuristic core reduction is applied\n depending on the command-line options. A *minimum weight*\n of the core is computed a...
Please provide a description of the function:def process_core(self): # updating the cost self.cost += self.minw # assumptions to remove self.garbage = set() if len(self.core_sels) != 1 or len(self.core_sums) > 0: # process selectors in the core ...
[ "\n The method deals with a core found previously in\n :func:`get_core`. Clause selectors ``self.core_sels`` and\n sum assumptions involved in the core are treated\n separately of each other. This is handled by calling\n methods :func:`process_sels` and :func:`...
Please provide a description of the function:def adapt_am1(self): # literal connections conns = collections.defaultdict(lambda: set([])) confl = [] # prepare connections for l1 in self.sels: st, props = self.oracle.propagate(assumptions=[l1], phase_saving=2...
[ "\n Detect and adapt intrinsic AtMost1 constraints. Assume\n there is a subset of soft clauses\n :math:`\\\\mathcal{S}'\\subseteq \\\\mathcal{S}` s.t.\n :math:`\\sum_{c\\in\\\\mathcal{S}'}{c\\leq 1}`, i.e. at most\n one of the clauses of :math:`\\\\mathcal{S}'`...
Please provide a description of the function:def trim_core(self): for i in range(self.trim): # call solver with core assumption only # it must return 'unsatisfiable' self.oracle.solve(assumptions=self.core) # extract a new core new_core = se...
[ "\n This method trims a previously extracted unsatisfiable\n core at most a given number of times. If a fixed point is\n reached before that, the method returns.\n " ]
Please provide a description of the function:def minimize_core(self): if self.minz and len(self.core) > 1: self.core = sorted(self.core, key=lambda l: self.wght[l]) self.oracle.conf_budget(1000) i = 0 while i < len(self.core): to_test = ...
[ "\n Reduce a previously extracted core and compute an\n over-approximation of an MUS. This is done using the\n simple deletion-based MUS extraction algorithm.\n\n The idea is to try to deactivate soft clauses of the\n unsatisfiable core one by one while checkin...
Please provide a description of the function:def exhaust_core(self, tobj): # the first case is simpler if self.oracle.solve(assumptions=[-tobj.rhs[1]]): return 1 else: self.cost += self.minw for i in range(2, len(self.rels)): # saving the pr...
[ "\n Exhaust core by increasing its bound as much as possible.\n Core exhaustion was originally referred to as *cover\n optimization* in [5]_.\n\n Given a totalizer object ``tobj`` representing a sum of\n some *relaxation* variables :math:`r\\in R` that augment\...
Please provide a description of the function:def process_sels(self): # new relaxation variables self.rels = [] for l in self.core_sels: if self.wght[l] == self.minw: # marking variable as being a part of the core # so that next time it is no...
[ "\n Process soft clause selectors participating in a new core.\n The negation :math:`\\\\neg{s}` of each selector literal\n :math:`s` participating in the unsatisfiable core is added\n to the list of relaxation literals, which will be later\n used to create a n...
Please provide a description of the function:def process_sums(self): for l in self.core_sums: if self.wght[l] == self.minw: # marking variable as being a part of the core # so that next time it is not used as an assump self.garbage.add(l) ...
[ "\n Process cardinality sums participating in a new core.\n Whenever necessary, some of the sum assumptions are\n removed or split (depending on the value of\n ``self.minw``). Deleted sums are marked as garbage and are\n dealt with in :func:`filter_assumps`.\n\...
Please provide a description of the function:def create_sum(self, bound=1): if self.solver != 'mc': # standard totalizer-based encoding # new totalizer sum t = ITotalizer(lits=self.rels, ubound=bound, top_id=self.topv) # updating top variable id self.t...
[ "\n Create a totalizer object encoding a cardinality\n constraint on the new list of relaxation literals obtained\n in :func:`process_sels` and :func:`process_sums`. The\n clauses encoding the sum of the relaxation literals are\n added to the SAT oracle. The su...
Please provide a description of the function:def update_sum(self, assump): # getting a totalizer object corresponding to assumption t = self.tobj[assump] # increment the current bound b = self.bnds[assump] + 1 if self.solver != 'mc': # the case of standard totalizer ...
[ "\n The method is used to increase the bound for a given\n totalizer sum. The totalizer object is identified by the\n input parameter ``assump``, which is an assumption literal\n associated with the totalizer object.\n\n The method increases the bound for the t...
Please provide a description of the function:def set_bound(self, tobj, rhs): # saving the sum and its weight in a mapping self.tobj[-tobj.rhs[rhs]] = tobj self.bnds[-tobj.rhs[rhs]] = rhs self.wght[-tobj.rhs[rhs]] = self.minw # adding a new assumption to force the sum t...
[ "\n Given a totalizer sum and its right-hand side to be\n enforced, the method creates a new sum assumption literal,\n which will be used in the following SAT oracle calls.\n\n :param tobj: totalizer sum\n :param rhs: right-hand side\n\n :type tobj: ...
Please provide a description of the function:def filter_assumps(self): self.sels = list(filter(lambda x: x not in self.garbage, self.sels)) self.sums = list(filter(lambda x: x not in self.garbage, self.sums)) self.bnds = {l: b for l, b in six.iteritems(self.bnds) if l not in self.garb...
[ "\n Filter out unnecessary selectors and sums from the list of\n assumption literals. The corresponding values are also\n removed from the dictionaries of bounds and weights.\n\n Note that assumptions marked as garbage are collected in\n the core processing met...
Please provide a description of the function:def init_wstr(self): # a mapping for stratified problem solving, # i.e. from a weight to a list of selectors self.wstr = collections.defaultdict(lambda: []) for s, w in six.iteritems(self.wght): self.wstr[w].append(s) ...
[ "\n Compute and initialize optimization levels for BLO and\n stratification. This method is invoked once, from the\n constructor of an object of :class:`RC2Stratified`. Given\n the weights of the soft clauses, the method divides the\n MaxSAT problem into severa...
Please provide a description of the function:def compute(self): done = 0 # levels done # first attempt to get an optimization level self.next_level() while self.levl != None and done < len(self.blop): # add more clauses done = self.activate_clauses(do...
[ "\n This method solves the MaxSAT problem iteratively. Each\n optimization level is tackled the standard way, i.e. by\n calling :func:`compute_`. A new level is started by\n calling :func:`next_level` and finished by calling\n :func:`finish_level`. Each new opt...
Please provide a description of the function:def next_level(self): if self.levl >= len(self.blop): self.levl = None while self.levl < len(self.blop) - 1: # number of selectors with weight less than current weight numc = sum([len(self.wstr[w]) for w in self....
[ "\n Compute the next optimization level (starting from the\n current one). The procedure represents a loop, each\n iteration of which checks whether or not one of the\n conditions holds:\n\n - partial BLO condition\n - stratification condition\n\n ...
Please provide a description of the function:def activate_clauses(self, beg): end = min(self.levl + 1, len(self.blop)) for l in range(beg, end): for sel in self.wstr[self.blop[l]]: if sel in self.bckp_set: self.sels.append(sel) e...
[ "\n This method is used for activating the clauses that belong\n to optimization levels up to the newly computed level. It\n also reactivates previously deactivated clauses (see\n :func:`process_sels` and :func:`process_sums` for\n details).\n " ]
Please provide a description of the function:def finish_level(self): # assumptions to remove self.garbage = set() # sum of weights of the remaining levels sumw = sum([w * len(self.wstr[w]) for w in self.blop[(self.levl + 1):]]) # trying to harden selectors and sums ...
[ "\n This method does postprocessing of the current\n optimization level after it is solved. This includes\n *hardening* some of the soft clauses (depending on their\n remaining weights) and also garbage collection.\n " ]
Please provide a description of the function:def process_am1(self, am1): # computing am1's weight self.minw = min(map(lambda l: self.wght[l], am1)) # pretending am1 to be a core, and the bound is its size - 1 self.core_sels, b = am1, len(am1) - 1 # incrementing the co...
[ "\n Due to the solving process involving multiple optimization\n levels to be treated individually, new soft clauses for\n the detected intrinsic AtMost1 constraints should be\n remembered. The method is a slightly modified version of\n the base method :func:`R...
Please provide a description of the function:def process_sels(self): # new relaxation variables self.rels = [] # selectors that should be deactivated (but not removed completely) to_deactivate = set([]) for l in self.core_sels: if self.wght[l] == self.minw...
[ "\n A redefined version of :func:`RC2.process_sels`. The only\n modification affects the clauses whose weight after\n splitting becomes less than the weight of the current\n optimization level. Such clauses are deactivated and to be\n reactivated at a later sta...
Please provide a description of the function:def process_sums(self): # sums that should be deactivated (but not removed completely) to_deactivate = set([]) for l in self.core_sums: if self.wght[l] == self.minw: # marking variable as being a part of the core...
[ "\n A redefined version of :func:`RC2.process_sums`. The only\n modification affects the clauses whose weight after\n splitting becomes less than the weight of the current\n optimization level. Such clauses are deactivated and to be\n reactivated at a later sta...
Please provide a description of the function:def _get_current_object(self): if not hasattr(self.__local, '__release_local__'): return self.__local() try: return getattr(self.__local, self.__name__) except AttributeError: raise RuntimeError('no object ...
[ "Return the current object. This is useful if you want the real\n object behind the proxy at a time for performance reasons or because\n you want to pass the object into a different context.\n " ]
Please provide a description of the function:def to_mime_message(self): msg = MIMEMultipart('alternative') msg['Subject'] = self._header(self._subject or '') msg['From'] = self._encoded(self._addrs_to_header([self._from])) msg['To'] = self._encoded(self._addrs_to_header(self._t...
[ "Returns the envelope as\n :py:class:`email.mime.multipart.MIMEMultipart`." ]
Please provide a description of the function:def add_attachment(self, file_path, mimetype=None): if not mimetype: mimetype, _ = mimetypes.guess_type(file_path) if mimetype is None: mimetype = 'application/octet-stream' type_maj, type_min = mimetype.split('/') ...
[ "Attaches a file located at *file_path* to the envelope. If\n *mimetype* is not specified an attempt to guess it is made. If nothing\n is guessed then `application/octet-stream` is used." ]
Please provide a description of the function:def send(self, *args, **kwargs): conn = SMTP(*args, **kwargs) send_result = conn.send(self) return conn, send_result
[ "Sends the envelope using a freshly created SMTP connection. *args*\n and *kwargs* are passed directly to :py:class:`envelopes.conn.SMTP`\n constructor.\n\n Returns a tuple of SMTP object and whatever its send method returns." ]
Please provide a description of the function:def is_connected(self): try: self._conn.noop() except (AttributeError, smtplib.SMTPServerDisconnected): return False else: return True
[ "Returns *True* if the SMTP connection is initialized and\n connected. Otherwise returns *False*" ]
Please provide a description of the function:def send(self, envelope): if not self.is_connected: self._connect() msg = envelope.to_mime_message() to_addrs = [envelope._addrs_to_header([addr]) for addr in envelope._to + envelope._cc + envelope._bcc] return self._con...
[ "Sends an *envelope*." ]
Please provide a description of the function:def __get_path_to_mecab_config(self): if six.PY2: path_mecab_config_dir = subprocess.check_output(['which', 'mecab-config']) path_mecab_config_dir = path_mecab_config_dir.strip().replace('/mecab-config', '') else: ...
[ "You get path into mecab-config\n " ]
Please provide a description of the function:def __check_mecab_dict_path(self): mecab_dic_cmd = "echo `{} --dicdir`".format(os.path.join(self._path_mecab_config, 'mecab-config')) try: if six.PY2: path_mecab_dict = subprocess.check_output( mecab_dic_cmd, shell=True ...
[ "check path to dict of Mecab in system environment\n ", "mecab dictionary path is not found with following command: {} \n You are not able to use additional dictionary. \n Still you are able to call mecab default dictionary" ]
Please provide a description of the function:def __CompileUserdict(self): path_mecab_dict = self.__check_mecab_dict_path() path_mecab_libexe = self.__check_mecab_libexe() cmCompileDict = u'{0}/mecab-dict-index -d {1}/ipadic -u {2} -f utf-8 -t utf-8 {3} > /dev/null'.format(path_mecab_li...
[ "* What you can do\n " ]
Please provide a description of the function:def __feature_parser(self, uni_feature, word_surface): list_feature_items = uni_feature.split((',')) # if word has no feature at all if len(list_feature_items)==1: return ('*'), ('*') pos1 = list_feature_items[0] pos2 = list_...
[ "\n Parse the POS feature output by Mecab\n :param uni_feature unicode:\n :return ( (pos1, pos2, pos3), word_stem ):\n " ]
Please provide a description of the function:def __postprocess_analyzed_result(self, string_mecab_parsed_result, is_feature, is_surface): # type: (text_type,bool,bool)->List[TokenizedResult] assert isinstance(string_mecab_parsed_result, str) check_tab_separated_line = lambda x: True if ...
[ "Extract surface word and feature from analyzed lines.\n Extracted results are returned with list, whose elements are TokenizedResult class\n [TokenizedResult]\n " ]
Please provide a description of the function:def __result_parser(self, analyzed_line, is_feature, is_surface): # type: (text_type,bool,bool)->TokenizedResult assert isinstance(analyzed_line, str) assert isinstance(is_feature, bool) assert isinstance(is_surface, bool) su...
[ "Extract surface word and feature from analyzed line.\n Extracted elements are returned with TokenizedResult class\n " ]
Please provide a description of the function:def tokenize(self, sentence, normalized=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=normalize_text): # type: (text_type, bool, bool, bool, bool, Call...
[ "* What you can do\n - Call mecab tokenizer, and return tokenized objects\n\n " ]
Please provide a description of the function:def __is_valid_pos(pos_tuple, valid_pos): # type: (Tuple[text_type,...],List[Tuple[text_type,...]])->bool def is_valid_pos(valid_pos_tuple): # type: (Tuple[text_type,...])->bool length_valid_pos_tuple = len(valid_pos_tuple) if valid_pos_t...
[ "This function checks token's pos is with in POS set that user specified.\n If token meets all conditions, Return True; else return False\n " ]
Please provide a description of the function:def filter_words(tokenized_obj, valid_pos, stopwords, check_field_name='stem'): # type: (TokenizedSenetence, List[Tuple[text_type,...]], List[text_type],text_type) -> FilteredObject assert isinstance(tokenized_obj, TokenizedSenetence) assert isinstance(valid...
[ "This function filter token that user don't want to take.\n Condition is stopword and pos.\n\n * Input\n - valid_pos\n - List of Tuple which has POS element to keep.\n - Keep in your mind, each tokenizer has different POS structure.\n >>> [('名詞', '固有名詞'), ('動詞', )]\n - stopwords\n ...
Please provide a description of the function:def __extend_token_object(self, token_object, is_denormalize=True, func_denormalizer=denormalize_text): # type: (TokenizedResult,bool,Callable[[str],str])->Tuple assert isinstance(token_obje...
[ "This method creates dict object from token object.\n " ]
Please provide a description of the function:def convert_list_object(self, is_denormalize=True, func_denormalizer=denormalize_text): # type: (bool,Callable[[str],str])->List[Union[str, Tuple[str,...]]] sentence_in_list_obj = [ ...
[ "* What you can do\n - You extract string object from TokenizedResult object\n\n * Args\n - is_denormalize: boolen object. True; it makes denormalize string\n - func_denormalizer: callable object. de-normalization function.\n " ]
Please provide a description of the function:def __convert_string_type(self, p_c_tuple): # type: (Tuple[text_type,...])->Tuple[text_type] if not isinstance(p_c_tuple, tuple): raise Exception('Pos condition expects tuple of string. However = {}'.format(p_c_tuple)) converted ...
[ "* What you can do\n - it normalizes string types into str\n ", "str into unicode if python2.x" ]
Please provide a description of the function:def __check_pos_condition(self, pos_condistion): # type: (List[Tuple[text_type, ...]])->List[Tuple[text_type, ...]] assert isinstance(pos_condistion, list) return [self.__convert_string_type(p_c_tuple) for p_c_tuple in pos_condistion]
[ "* What you can do\n - Check your pos condition\n - It converts character type into unicode if python version is 2.x\n " ]
Please provide a description of the function:def filter(self, pos_condition=None, stopwords=None, is_normalize=True, func_normalizer=normalize_text, check_field_name='stem'): # type: (List[Tuple[text_type,...]], List[text_type], bool, Ca...
[ "* What you can do\n - It filters out token which does NOT meet the conditions (stopwords & part-of-speech tag)\n - Under python2.x, pos_condition & stopwords are converted into unicode type.\n\n * Parameters\n - pos_condition: list of part-of-speech(pos) condition. The pos condition is ...
Please provide a description of the function:def denormalize_text(input_text): # type: (text_type)->text_type if input_text in STRING_EXCEPTION: return input_text else: return jaconv.z2h(input_text, kana=False, ascii=True, digit=True)
[ "* What you can do\n - It converts text into standard japanese writing way\n\n * Note\n - hankaku-katakana is to zenkaku-katakana\n - zenkaku-eisu is to hankaku-eisu\n " ]
Please provide a description of the function:def normalize_text(input_text, dictionary_mode='ipadic', new_line_replaced='。', is_replace_eos=True, is_kana=True, is_ascii=True, is_digit=True): # type: (te...
[ "* What you can do\n - It converts input-text into normalized-text which is good for tokenizer input.\n\n * Params\n - new_line_replaced: a string which replaces from \\n string.\n " ]
Please provide a description of the function:def normalize_text_normal_ipadic(input_text, kana=True, ascii=True, digit=True): # type: (text_type,bool,bool,bool)->text_type return jaconv.h2z(input_text, kana=kana, ascii=ascii, digit=digit)
[ "\n * All hankaku Katanaka is converted into Zenkaku Katakana\n * All hankaku English alphabet and numberc string are converted into Zenkaku one\n " ]
Please provide a description of the function:def __monkey_patch_juman_lines(self, input_str): # type: (text_type)->text_type assert isinstance(self.juman, pyknp.Juman) if not self.juman.socket and not self.juman.subprocess: if self.juman.server is not None: s...
[ "* What you can do\n - It overwrites juman_line() method because this method causes TypeError in python3\n " ]
Please provide a description of the function:def tokenize(self, sentence, normalize=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=text_preprocess.normalize_text): # type: (text_pr...
[ "This method returns tokenized result.\n If return_list==True(default), this method returns list whose element is tuple consisted with word_stem and POS.\n If return_list==False, this method returns TokenizedSenetence object.\n " ]
Please provide a description of the function:def on_timeout(limit, handler=handler_func, hint=None): def notify_handler(signum, frame): handler("'%s' is not finished in %d second(s)." % (hint, limit)) def __decorator(function): def __wrapper(*args, **kwargs): import signal ...
[ "\n 指定した実行時間に終了しなかった場合、handlerをhint/limitを引数にして呼び出します\n @on_timeout(limit=3600, handler=notify_func, hint=u'長い計算')\n def long_time_function():\n " ]
Please provide a description of the function:def call_juman_interface(self, input_str): # type: (text_type) -> MList if isinstance(self.jumanpp_obj, Juman): ml_token_object = self.jumanpp_obj.analysis(input_str=input_str) elif isinstance(self.jumanpp_obj, JumanppHnadler): ...
[ "* What you can do\n - You call Juman tokenizer interface.\n\n * Output\n - pyknp.MList\n ", "Unix process is down by any reason." ]
Please provide a description of the function:def tokenize(self, sentence, normalize=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=text_preprocess.normalize_text): # type: (text_type, bool, bool, b...
[ "* What you can do\n -\n " ]
Please provide a description of the function:def __extract_morphological_information(self, kytea_tags_tuple, is_feature): # type: (Tuple[text_type,List[Any]], bool) -> TokenizedResult assert isinstance(kytea_tags_tuple, tuple) assert isinstance(is_feature, bool) surface = self....
[ "This method extracts morphlogical information from token object.\n " ]
Please provide a description of the function:def tokenize(self, sentence, normalize=True, is_feature=False, is_surface=False, return_list=False, func_normalizer=text_preprocess.normalize_text): # type: (text_type, bool, bool, b...
[ "This method returns tokenized result.\n If return_list==True(default), this method returns list whose element is tuple consisted with word_stem and POS.\n If return_list==False, this method returns TokenizedSenetence object.\n " ]
Please provide a description of the function:def extract_morphological_information(mrph_object, is_feature, is_surface): # type: (pyknp.Morpheme, bool, bool) -> TokenizedResult assert isinstance(mrph_object, pyknp.Morpheme) assert isinstance(is_feature, bool) assert isinstance(is_surface, bool) ...
[ "This method extracts morphlogical information from token object.\n " ]
Please provide a description of the function:def feature_parser(uni_feature, word_surface): # type: (text_type, text_type) -> Tuple[Tuple[text_type, text_type, text_type], text_type] list_feature_items = uni_feature.split(',') # if word has no feature at all if len(list_feature_items) == 1: return ...
[ "\n Parse the POS feature output by Mecab\n :param uni_feature unicode:\n :return ( (pos1, pos2, pos3), word_stem ):\n " ]
Please provide a description of the function:def launch_process(self, command): # type: (Union[bytes,text_type])->None if not self.option is None: command_plus_option = self.command + " " + self.option else: command_plus_option = self.command if six.PY3:...
[ "* What you can do\n - It starts process and keep it.\n " ]
Please provide a description of the function:def __query(self, input_string): # type: (text_type)->text_type signal.signal(signal.SIGALRM, self.__notify_handler) signal.alarm(self.timeout_second) self.process_analyzer.sendline(input_string) buffer = "" while True...
[ "* What you can do\n - It takes the result of Juman++\n - This function monitors time which takes for getting the result.\n ", "Skip if process returns the same input string" ]
Please provide a description of the function:def notify(notification, value=None, unset_environment=False): if not isinstance(notification, Notification): raise TypeError("state must be an instance of Notification") state = notification.value if state.constant is not None and value: ...
[ " Send notification to systemd daemon\n\n :type notification: Notification\n :type value: int\n :type unset_environment: bool \n :param value: str or int value for non constant notifications\n :returns None\n " ]
Please provide a description of the function:def write(message, priority=Priority.INFO): priority = int(Priority(int(priority))) send(priority=priority, message=message)
[ " Write message into systemd journal \n :type priority: Priority\n :type message: str\n " ]
Please provide a description of the function:def expand_source_paths(paths): for src_path in paths: # only track the source path if we can find it to avoid double-reloads # when the source and the compiled path change because on some # platforms they are not changed at the same time ...
[ " Convert pyc files into their source equivalents." ]
Please provide a description of the function:def iter_module_paths(modules=None): modules = modules or list(sys.modules.values()) for module in modules: try: filename = module.__file__ except (AttributeError, ImportError): # pragma: no cover continue if file...
[ " Yield paths of all imported modules." ]
Please provide a description of the function:def update_paths(self): new_paths = [] with self.lock: for path in expand_source_paths(iter_module_paths()): if path not in self.paths: self.paths.add(path) new_paths.append(path) ...
[ " Check sys.modules for paths to add to our path set." ]
Please provide a description of the function:def search_traceback(self, tb): new_paths = [] with self.lock: for filename, line, funcname, txt in traceback.extract_tb(tb): path = os.path.abspath(filename) if path not in self.paths: ...
[ " Inspect a traceback for new paths to add to our path set." ]
Please provide a description of the function:def args_from_interpreter_flags(): flag_opt_map = { 'debug': 'd', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'quiet...
[ "\n Return a list of command-line arguments reproducing the current\n settings in sys.flags and sys.warnoptions.\n\n " ]
Please provide a description of the function:def spawn(spec, kwargs, pass_fds=()): r, w = os.pipe() for fd in [r] + list(pass_fds): set_inheritable(fd, True) preparation_data = get_preparation_data() r_handle = get_handle(r) args, env = get_command_line(pipe_handle=r_handle) proce...
[ "\n Invoke a python function in a subprocess.\n\n " ]
Please provide a description of the function:def get_watchman_sockpath(binpath='watchman'): path = os.getenv('WATCHMAN_SOCK') if path: return path cmd = [binpath, '--output-encoding=json', 'get-sockname'] result = subprocess.check_output(cmd) result = json.loads(result) return resu...
[ " Find the watchman socket or raise." ]
Please provide a description of the function:def start_reloader( worker_path, reload_interval=1, shutdown_interval=default, verbose=1, logger=None, monitor_factory=None, worker_args=None, worker_kwargs=None, ignore_files=None, ): if is_active(): return get_reloader()...
[ "\n Start a monitor and then fork a worker process which starts by executing\n the importable function at ``worker_path``.\n\n If this function is called from a worker process that is already being\n monitored then it will return a reference to the current\n :class:`hupper.interfaces.IReloaderProxy` ...
Please provide a description of the function:def run(self): self._capture_signals() self._start_monitor() try: while True: if not self._run_worker(): self._wait_for_changes() time.sleep(self.reload_interval) except ...
[ "\n Execute the reloader forever, blocking the current thread.\n\n This will invoke ``sys.exit(1)`` if interrupted.\n\n " ]
Please provide a description of the function:def run_once(self): self._capture_signals() self._start_monitor() try: self._run_worker() except KeyboardInterrupt: return finally: self._stop_monitor() self._restore_signals()
[ "\n Execute the worker once.\n\n This method will return after a file change is detected.\n\n " ]
Please provide a description of the function:def consultar_cep(cep, ambiente=PRODUCAO): if ambiente not in URL: raise KeyError('Ambiente inválido! Valor deve ser 1 para produção e 2 ' 'para homologação') try: with warnings.catch_warnings(): # Desabilitam...
[ "Retorna o endereço correspondente ao número de CEP informado.\n\n Arguments:\n cep {str} -- CEP a ser consultado.\n\n Keyword Arguments:\n ambiente {int} -- Indica qual será o webservice utilizado na consulta de CEP. Valor default é PRODUCAO (default: {PRODUCAO})\n\n Raises:\n KeyErro...
Please provide a description of the function:def formatar_cep(cep): if not isinstance(cep, str) or not cep: raise ValueError('CEP deve ser uma string não vazia ' 'contendo somente numeros') return CARACTERES_NUMERICOS.sub('', cep)
[ "Formata CEP, removendo qualquer caractere não numérico.\n\n Arguments:\n cep {str} -- CEP a ser formatado.\n\n Raises:\n ValueError -- Quando a string esta vazia ou não contem numeros.\n\n Returns:\n str -- string contendo o CEP formatado.\n " ]
Please provide a description of the function:def malloc(self, key, shape, dtype): if key not in self._memory or self._memory[key].shape != shape or self._memory[key].dtype != dtype: self._memory[key] = Shmem(key, shape, dtype, self._uuid) return self._memory[key].np_array
[ "Allocates a block of shared memory, and returns a numpy array whose data corresponds with that block.\n\n Args:\n key (str): The key to identify the block.\n shape (list of int): The shape of the numpy array to allocate.\n dtype (type): The numpy data type (e.g. np.float32)....
Please provide a description of the function:def package_info(pkg_name): indent = " " for config, _ in _iter_packages(): if pkg_name == config["name"]: print("Package:", pkg_name) print(indent, "Platform:", config["platform"]) print(indent, "Version:", config["v...
[ "Prints the information of a package.\n\n Args:\n pkg_name (str): The name of the desired package to get information\n " ]
Please provide a description of the function:def world_info(world_name, world_config=None, initial_indent="", next_indent=" "): if world_config is None: for config, _ in _iter_packages(): for world in config["maps"]: if world["name"] == world_name: world...
[ "Gets and prints the information of a world.\n\n Args:\n world_name (str): the name of the world to retrieve information for\n world_config (dict optional): A dictionary containing the world's configuration. Will find the config if None. Defaults to None.\n initial_indent (str optional): Thi...
Please provide a description of the function:def install(package_name): holodeck_path = util.get_holodeck_path() binary_website = "https://s3.amazonaws.com/holodeckworlds/" if package_name not in packages: raise HolodeckException("Unknown package name " + package_name) package_url = packag...
[ "Installs a holodeck package.\n\n Args:\n package_name (str): The name of the package to install\n " ]
Please provide a description of the function:def remove(package_name): if package_name not in packages: raise HolodeckException("Unknown package name " + package_name) for config, path in _iter_packages(): if config["name"] == package_name: shutil.rmtree(path)
[ "Removes a holodeck package.\n\n Args:\n package_name (str): the name of the package to remove\n " ]
Please provide a description of the function:def make(world_name, gl_version=GL_VERSION.OPENGL4, window_res=None, cam_res=None, verbose=False): holodeck_worlds = _get_worlds_map() if world_name not in holodeck_worlds: raise HolodeckException("Invalid World Name") param_dict = copy(holodeck_wor...
[ "Creates a holodeck environment using the supplied world name.\n\n Args:\n world_name (str): The name of the world to load as an environment. Must match the name of a world in an\n installed package.\n gl_version (int, optional): The OpenGL version to use (Linux only). Defaults to GL_VER...
Please provide a description of the function:def unlink(self): if os.name == "posix": self.__linux_unlink__() elif os.name == "nt": self.__windows_unlink__() else: raise HolodeckException("Currently unsupported os: " + os.name)
[ "unlinks the shared memory" ]
Please provide a description of the function:def to_json(self): commands = ",".join(map(lambda x: x.to_json(), self._commands)) return "{\"commands\": [" + commands + "]}"
[ "\n Returns:\n str: Json for commands array object and all of the commands inside the array." ]
Please provide a description of the function:def add_number_parameters(self, number): if isinstance(number, list): for x in number: self.add_number_parameters(x) return self._parameters.append("{ \"value\": " + str(number) + " }")
[ "Add given number parameters to the internal list.\n\n Args:\n number (list of int or list of float): A number or list of numbers to add to the parameters.\n " ]
Please provide a description of the function:def add_string_parameters(self, string): if isinstance(string, list): for x in string: self.add_string_parameters(x) return self._parameters.append("{ \"value\": \"" + string + "\" }")
[ "Add given string parameters to the internal list.\n\n Args:\n string (list of str or str): A string or list of strings to add to the parameters.\n " ]
Please provide a description of the function:def set_type(self, agent_type): type_str = SpawnAgentCommand.__type_keys[agent_type] self.add_string_parameters(type_str)
[ "Set the type of agent to spawn in Holodeck. Currently accepted agents are: DiscreteSphereAgent, UAVAgent,\n and AndroidAgent.\n\n Args:\n agent_type (str): The type of agent to spawn.\n " ]
Please provide a description of the function:def set_type(self, weather_type): weather_type.lower() exists = self.has_type(weather_type) if exists: self.add_string_parameters(weather_type)
[ "Set the weather type.\n\n Args:\n weather_type (str): The weather type.\n " ]
Please provide a description of the function:def uav_example(): env = holodeck.make("UrbanCity") # This changes the control scheme for the uav env.set_control_scheme("uav0", ControlSchemes.UAV_ROLL_PITCH_YAW_RATE_ALT) for i in range(10): env.reset() # This command tells the UAV t...
[ "A basic example of how to use the UAV agent." ]