Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def QA_SU_save_future_min(client=DATABASE, ui_log=None, ui_progress=None):
future_list = [
item for item in QA_fetch_get_future_list().code.unique().tolist()
if str(item)[-2:] in ['L8',
'L9']
]
coll = client.fut... | [
"save future_min\n\n Keyword Arguments:\n client {[type]} -- [description] (default: {DATABASE})\n "
] |
Please provide a description of the function:def do_shell(self, arg):
"run a shell commad"
print(">", arg)
sub_cmd = subprocess.Popen(arg, shell=True, stdout=subprocess.PIPE)
print(sub_cmd.communicate()[0]) | [] |
Please provide a description of the function:def QA_fetch_stock_min_adv(
code,
start, end=None,
frequence='1min',
if_drop_index=True,
# 🛠 todo collections 参数没有用到, 且数据库是固定的, 这个变量后期去掉
collections=DATABASE.stock_min):
'''
'获取股票分钟线'
:param code: 字符串str eg 600085... | [] |
Please provide a description of the function:def QA_fetch_stock_day_full_adv(date):
'''
'返回全市场某一天的数据'
:param date:
:return: QA_DataStruct_Stock_day类 型数据
'''
# 🛠 todo 检查日期data参数
res = QA_fetch_stock_full(date, 'pd')
if res is None:
print("QA Error QA_fetch_stock_day_full_adv para... | [] |
Please provide a description of the function:def QA_fetch_index_day_adv(
code,
start, end=None,
if_drop_index=True,
# 🛠 todo collections 参数没有用到, 且数据库是固定的, 这个变量后期去掉
collections=DATABASE.index_day):
'''
:param code: code: 字符串str eg 600085
:param start: 字符串str 开始日期 eg... | [] |
Please provide a description of the function:def QA_fetch_index_min_adv(
code,
start, end=None,
frequence='1min',
if_drop_index=True,
collections=DATABASE.index_min):
'''
'获取股票分钟线'
:param code:
:param start:
:param end:
:param frequence:
:param if_drop... | [] |
Please provide a description of the function:def QA_fetch_stock_list_adv(collections=DATABASE.stock_list):
'''
'获取股票列表'
:param collections: mongodb 数据库
:return: DataFrame
'''
stock_list_items = QA_fetch_stock_list(collections)
if len(stock_list_items) == 0:
print("QA Error QA_fetch_s... | [] |
Please provide a description of the function:def QA_fetch_index_list_adv(collections=DATABASE.index_list):
'''
'获取股票列表'
:param collections: mongodb 数据库
:return: DataFrame
'''
index_list_items = QA_fetch_index_list(collections)
if len(index_list_items) == 0:
print("QA Error QA_fetch_i... | [] |
Please provide a description of the function:def QA_fetch_future_day_adv(
code,
start, end=None,
if_drop_index=True,
# 🛠 todo collections 参数没有用到, 且数据库是固定的, 这个变量后期去掉
collections=DATABASE.index_day):
'''
:param code: code: 字符串str eg 600085
:param start: 字符串str 开始日期 e... | [] |
Please provide a description of the function:def QA_fetch_future_min_adv(
code,
start, end=None,
frequence='1min',
if_drop_index=True,
collections=DATABASE.future_min):
'''
'获取股票分钟线'
:param code:
:param start:
:param end:
:param frequence:
:param if_dr... | [] |
Please provide a description of the function:def QA_fetch_future_list_adv(collections=DATABASE.future_list):
'''
'获取股票列表'
:param collections: mongodb 数据库
:return: DataFrame
'''
future_list_items = QA_fetch_future_list()
if len(future_list_items) == 0:
print("QA Error QA_fetch_future_... | [] |
Please provide a description of the function:def QA_fetch_stock_block_adv(code=None, blockname=None, collections=DATABASE.stock_block):
'''
返回板块 ❌
:param code:
:param blockname:
:param collections: 默认数据库 stock_block
:return: QA_DataStruct_Stock_block
'''
if code is not None and blockname... | [] |
Please provide a description of the function:def QA_fetch_stock_realtime_adv(code=None,
num=1,
collections=DATABASE.get_collection('realtime_{}'.format(datetime.date.today()))):
'''
返回当日的上下五档, code可以是股票可以是list, num是每个股票获取的数量
:param code:
:p... | [] |
Please provide a description of the function:def QA_fetch_financial_report_adv(code, start, end=None, ltype='EN'):
if end is None:
return QA_DataStruct_Financial(QA_fetch_financial_report(code, start, ltype=ltype))
else:
series = pd.Series(
data=month_data, index=pd.to_datetim... | [
"高级财务查询接口\n Arguments:\n code {[type]} -- [description]\n start {[type]} -- [description]\n Keyword Arguments:\n end {[type]} -- [description] (default: {None})\n "
] |
Please provide a description of the function:def QA_fetch_stock_financial_calendar_adv(code, start="all", end=None, format='pd', collections=DATABASE.report_calendar):
'获取股票日线'
#code= [code] if isinstance(code,str) else code
end = start if end is None else end
start = str(start)[0:10]
end = str(end)... | [] |
Please provide a description of the function:def QA_fetch_get_tdxtraderecord(file):
try:
with open('./20180606.csv', 'r') as f:
l = csv.reader(f)
data = [item for item in l]
res = pd.DataFrame(data[1:], columns=data[0])
return res
except:
raise IOErr... | [
"\n QUANTAXIS 读取历史交易记录 通达信 历史成交-输出-xlsfile--转换csvfile\n "
] |
Please provide a description of the function:def AROON(DataFrame, N=14):
ar_up, ar_down = talib.AROON(DataFrame.high.values, DataFrame.low.values, N)
return pd.DataFrame({'AROON_UP': ar_up,'AROON_DOWN': ar_down}, index=DataFrame.index) | [
"阿隆指标\n \n Arguments:\n DataFrame {[type]} -- [description]\n \n Keyword Arguments:\n N {int} -- [description] (default: {14})\n \n Returns:\n [type] -- [description]\n "
] |
Please provide a description of the function:def get_commission_coeff(self, code):
return max(self.get_code(code).get('commission_coeff_peramount'),
self.get_code(code).get('commission_coeff_pervol')) | [
"\n 当前无法区分是百分比还是按手数收费,不过可以拿到以后自行判断\n "
] |
Please provide a description of the function:def import_trade(self, trade):
for item in trade:
self.make_deal(item.code, item.datetime, item.amount,
item.towards, item.price.item.order_model, item.amount_model) | [
"\n trade是一个可迭代的list/generator\n "
] |
Please provide a description of the function:def make_deal(self, code, datetime, amount=100, towards=ORDER_DIRECTION.BUY, price=0, order_model=ORDER_MODEL.MARKET, amount_model=AMOUNT_MODEL.BY_AMOUNT):
self.account.receive_deal(self.backtest_broker.receive_order(QA_Event(order=self.account.send_order(
... | [
"\n 这是一个一定会成交,并且立刻结转(及t+0)的交易入口\n "
] |
Please provide a description of the function:def cancel(self):
self.cancel_amount = self.amount - self.trade_amount
if self.trade_amount == 0:
# 未交易 直接订单全撤
self._status = ORDER_STATUS.CANCEL_ALL
else:
# 部分交易 剩余订单全撤
self._status = ORDER_S... | [
"撤单\n\n Arguments:\n amount {int} -- 撤单数量\n "
] |
Please provide a description of the function:def failed(self, reason=None):
# 订单创建失败(如废单/场外废单/价格高于涨停价/价格低于跌停价/通讯失败)
self._status = ORDER_STATUS.FAILED
self.reason = str(reason) | [
"失败订单(未成功创建入broker)\n\n Arguments:\n reason {str} -- 失败原因\n "
] |
Please provide a description of the function:def trade(self, trade_id, trade_price, trade_amount, trade_time):
if self.status in [ORDER_STATUS.SUCCESS_PART, ORDER_STATUS.QUEUED]:
trade_amount = int(trade_amount)
trade_id = str(trade_id)
if trade_amount < 1:
... | [
"trade 状态\n\n Arguments:\n amount {[type]} -- [description]\n "
] |
Please provide a description of the function:def to_otgdict(self):
return {
"aid": "insert_order", # //必填, 下单请求
# //必填, 需要与登录用户名一致, 或为登录用户的子账户(例如登录用户为user1, 则报单 user_id 应当为 user1 或 user1.some_unit)
"user_id": self.account_cookie,
# //必填, ... | [
"{\n \"aid\": \"insert_order\", # //必填, 下单请求\n # //必填, 需要与登录用户名一致, 或为登录用户的子账户(例如登录用户为user1, 则报单 user_id 应当为 user1 或 user1.some_unit)\n \"user_id\": account_cookie,\n # //必填, 委托单号, 需确保在一个账号中不重复, 限长512字节\n \"order_id\": order_... |
Please provide a description of the function:def from_otgformat(self, otgOrder):
self.order_id = otgOrder.get('order_id')
self.account_cookie = otgOrder.get('user_id')
self.exchange_id = otgOrder.get('exchange_id')
self.code = str(otgOrder.get('instrument_id')).upper()
s... | [
"[summary]\n\n Arguments:\n otgOrder {[type]} -- [description]\n\n\n {'seqno': 6,\n 'user_id': '106184',\n 'order_id': 'WDRB_QA01_FtNlyBem',\n 'exchange_id': 'SHFE',\n 'instrument_id': 'rb1905',\n 'direction': 'SELL',\n 'offset': 'OPEN',\n 'v... |
Please provide a description of the function:def from_dict(self, order_dict):
'''
从字段类型的字段 填充 对象的字段
:param order_dict: dict 类型
:return: self QA_Order
'''
try:
# QA_util_log_info('QA_ORDER CHANGE: from {} change to {}'.format(
# self.order_id, ... | [] |
Please provide a description of the function:def insert_order(self, order):
'''
:param order: QA_Order类型
:return:
'''
#print(" *>> QAOrder!insert_order {}".format(order))
# QUEUED = 300 # queued 用于表示在order_queue中 实际表达的意思是订单存活 待成交
#order.status = ORDER_STATUS... | [] |
Please provide a description of the function:def pending(self):
'''
600 废单 未委托成功
200 委托成功,完全交易
203 委托成功,未完全成功
300 委托队列 待成交
400 已撤单
500 服务器撤单/每日结算
订单生成(100) -- 废单(600)
订单生成(100) -- 进入待成交队列(300) -- 完全成交(200) -- 每日结算(500)-- 死亡
订单生成(100) -- 进... | [] |
Please provide a description of the function:def _QA_data_stock_to_fq(bfq_data, xdxr_data, fqtype):
'使用数据库数据进行复权'
info = xdxr_data.query('category==1')
bfq_data = bfq_data.assign(if_trade=1)
if len(info) > 0:
data = pd.concat(
[
bfq_data,
info.loc[bfq... | [] |
Please provide a description of the function:def QA_data_stock_to_fq(__data, type_='01'):
def __QA_fetch_stock_xdxr(
code,
format_='pd',
collections=DATABASE.stock_xdxr
):
'获取股票除权信息/数据库'
try:
data = pd.DataFrame(
[item for item in ... | [] |
Please provide a description of the function:def get_response(self, statement=None, **kwargs):
Statement = self.storage.get_object('statement')
additional_response_selection_parameters = kwargs.pop('additional_response_selection_parameters', {})
persist_values_to_response = kwargs.pop... | [
"\n Return the bot's response based on the input.\n\n :param statement: An statement object or string.\n :returns: A response to the input.\n :rtype: Statement\n\n :param additional_response_selection_parameters: Parameters to pass to the\n chat bot's logic adapters to ... |
Please provide a description of the function:def generate_response(self, input_statement, additional_response_selection_parameters=None):
Statement = self.storage.get_object('statement')
results = []
result = None
max_confidence = -1
for adapter in self.logic_adapters:... | [
"\n Return a response based on a given input statement.\n\n :param input_statement: The input statement to be processed.\n "
] |
Please provide a description of the function:def learn_response(self, statement, previous_statement=None):
if not previous_statement:
previous_statement = statement.in_response_to
if not previous_statement:
previous_statement = self.get_latest_response(statement.convers... | [
"\n Learn that the statement provided is a valid response.\n "
] |
Please provide a description of the function:def serialize(self):
data = {}
for field_name in self.get_statement_field_names():
format_method = getattr(self, 'get_{}'.format(
field_name
), None)
if format_method:
data[field_n... | [
"\n :returns: A dictionary representation of the statement object.\n :rtype: dict\n "
] |
Please provide a description of the function:def import_module(dotted_path):
import importlib
module_parts = dotted_path.split('.')
module_path = '.'.join(module_parts[:-1])
module = importlib.import_module(module_path)
return getattr(module, module_parts[-1]) | [
"\n Imports the specified module based on the\n dot notated import path for the module.\n "
] |
Please provide a description of the function:def initialize_class(data, *args, **kwargs):
if isinstance(data, dict):
import_path = data.get('import_path')
data.update(kwargs)
Class = import_module(import_path)
return Class(*args, **data)
else:
Class = import_module(... | [
"\n :param data: A string or dictionary containing a import_path attribute.\n "
] |
Please provide a description of the function:def validate_adapter_class(validate_class, adapter_class):
from chatterbot.adapters import Adapter
# If a dictionary was passed in, check if it has an import_path attribute
if isinstance(validate_class, dict):
if 'import_path' not in validate_class... | [
"\n Raises an exception if validate_class is not a\n subclass of adapter_class.\n\n :param validate_class: The class to be validated.\n :type validate_class: class\n\n :param adapter_class: The class type to check against.\n :type adapter_class: class\n\n :raises: Adapter.InvalidAdapterTypeExce... |
Please provide a description of the function:def get_response_time(chatbot, statement='Hello'):
import time
start_time = time.time()
chatbot.get_response(statement)
return time.time() - start_time | [
"\n Returns the amount of time taken for a given\n chat bot to return a response.\n\n :param chatbot: A chat bot instance.\n :type chatbot: ChatBot\n\n :returns: The response time in seconds.\n :rtype: float\n "
] |
Please provide a description of the function:def print_progress_bar(description, iteration_counter, total_items, progress_bar_length=20):
import sys
percent = float(iteration_counter) / total_items
hashes = '#' * int(round(percent * progress_bar_length))
spaces = ' ' * (progress_bar_length - len(h... | [
"\n Print progress bar\n :param description: Training description\n :type description: str\n\n :param iteration_counter: Incremental counter\n :type iteration_counter: int\n\n :param total_items: total number items\n :type total_items: int\n\n :param progress_bar_length: Progress bar length\... |
Please provide a description of the function:def get_unit(self, ureg, unit_variations):
for unit in unit_variations:
try:
return getattr(ureg, unit)
except Exception:
continue
return None | [
"\n Get the first match unit metric object supported by pint library\n given a variation of unit metric names (Ex:['HOUR', 'hour']).\n\n :param ureg: unit registry which units are defined and handled\n :type ureg: pint.registry.UnitRegistry object\n\n :param unit_variations: A lis... |
Please provide a description of the function:def get_valid_units(self, ureg, from_unit, target_unit):
from_unit_variations = [from_unit.lower(), from_unit.upper()]
target_unit_variations = [target_unit.lower(), target_unit.upper()]
from_unit = self.get_unit(ureg, from_unit_variations)
... | [
"\n Returns the firt match `pint.unit.Unit` object for from_unit and\n target_unit strings from a possible variation of metric unit names\n supported by pint library.\n\n :param ureg: unit registry which units are defined and handled\n :type ureg: `pint.registry.UnitRegistry`\n\n ... |
Please provide a description of the function:def handle_matches(self, match):
response = Statement(text='')
from_parsed = match.group("from")
target_parsed = match.group("target")
n_statement = match.group("number")
if n_statement == 'a' or n_statement == 'an':
... | [
"\n Returns a response statement from a matched input statement.\n\n :param match: It is a valid matched pattern from the input statement\n :type: `_sre.SRE_Match`\n "
] |
Please provide a description of the function:def get_default_response(self, input_statement):
from random import choice
if self.default_responses:
response = choice(self.default_responses)
else:
try:
response = self.chatbot.storage.get_random()
... | [
"\n This method is called when a logic adapter is unable to generate any\n other meaningful response.\n "
] |
Please provide a description of the function:def time_question_features(self, text):
features = {}
# A list of all words from the known sentences
all_words = " ".join(self.positive + self.negative).split()
# A list of the first word in each of the known sentence
all_fi... | [
"\n Provide an analysis of significant features in the string.\n "
] |
Please provide a description of the function:def can_process(self, statement):
response = self.process(statement)
self.cache[statement.text] = response
return response.confidence == 1 | [
"\n Determines whether it is appropriate for this\n adapter to respond to the user input.\n "
] |
Please provide a description of the function:def process(self, statement, additional_response_selection_parameters=None):
from mathparse import mathparse
input_text = statement.text
# Use the result cached by the process method if it exists
if input_text in self.cache:
... | [
"\n Takes a statement string.\n Returns the equation from the statement with the mathematical terms solved.\n "
] |
Please provide a description of the function:def get_recent_repeated_responses(chatbot, conversation, sample=10, threshold=3, quantity=3):
from collections import Counter
# Get the most recent statements from the conversation
conversation_statements = list(chatbot.storage.filter(
conversation=... | [
"\n A filter that eliminates possibly repetitive responses to prevent\n a chat bot from repeating statements that it has recently said.\n "
] |
Please provide a description of the function:def get_most_frequent_response(input_statement, response_list, storage=None):
matching_response = None
occurrence_count = -1
logger = logging.getLogger(__name__)
logger.info('Selecting response with greatest number of occurrences.')
for statement i... | [
"\n :param input_statement: A statement, that closely matches an input to the chat bot.\n :type input_statement: Statement\n\n :param response_list: A list of statement options to choose a response from.\n :type response_list: list\n\n :param storage: An instance of a storage adapter to allow the res... |
Please provide a description of the function:def get_first_response(input_statement, response_list, storage=None):
logger = logging.getLogger(__name__)
logger.info('Selecting first response from list of {} options.'.format(
len(response_list)
))
return response_list[0] | [
"\n :param input_statement: A statement, that closely matches an input to the chat bot.\n :type input_statement: Statement\n\n :param response_list: A list of statement options to choose a response from.\n :type response_list: list\n\n :param storage: An instance of a storage adapter to allow the res... |
Please provide a description of the function:def get_random_response(input_statement, response_list, storage=None):
from random import choice
logger = logging.getLogger(__name__)
logger.info('Selecting a response from list of {} options.'.format(
len(response_list)
))
return choice(resp... | [
"\n :param input_statement: A statement, that closely matches an input to the chat bot.\n :type input_statement: Statement\n\n :param response_list: A list of statement options to choose a response from.\n :type response_list: list\n\n :param storage: An instance of a storage adapter to allow the res... |
Please provide a description of the function:def compare(self, statement_a, statement_b):
# Return 0 if either statement has a falsy text value
if not statement_a.text or not statement_b.text:
return 0
# Get the lowercase version of both strings
statement_a_text = ... | [
"\n Compare the two input statements.\n\n :return: The percent of similarity between the text of the statements.\n :rtype: float\n "
] |
Please provide a description of the function:def compare(self, statement_a, statement_b):
document_a = self.nlp(statement_a.text)
document_b = self.nlp(statement_b.text)
return document_a.similarity(document_b) | [
"\n Compare the two input statements.\n\n :return: The percent of similarity between the closest synset distance.\n :rtype: float\n "
] |
Please provide a description of the function:def compare(self, statement_a, statement_b):
# Make both strings lowercase
document_a = self.nlp(statement_a.text.lower())
document_b = self.nlp(statement_b.text.lower())
statement_a_lemmas = set([
token.lemma_ for token ... | [
"\n Return the calculated similarity of two\n statements based on the Jaccard index.\n "
] |
Please provide a description of the function:def get_statement_model(self):
from chatterbot.conversation import Statement
# Create a storage-aware statement
statement = Statement
statement.storage = self
return statement | [
"\n Return the class for the statement model.\n "
] |
Please provide a description of the function:def mongo_to_object(self, statement_data):
Statement = self.get_model('statement')
statement_data['id'] = statement_data['_id']
return Statement(**statement_data) | [
"\n Return Statement object when given data\n returned from Mongo DB.\n "
] |
Please provide a description of the function:def filter(self, **kwargs):
import pymongo
page_size = kwargs.pop('page_size', 1000)
order_by = kwargs.pop('order_by', None)
tags = kwargs.pop('tags', [])
exclude_text = kwargs.pop('exclude_text', None)
exclude_text_w... | [
"\n Returns a list of statements in the database\n that match the parameters specified.\n "
] |
Please provide a description of the function:def create(self, **kwargs):
Statement = self.get_model('statement')
if 'tags' in kwargs:
kwargs['tags'] = list(set(kwargs['tags']))
if 'search_text' not in kwargs:
kwargs['search_text'] = self.tagger.get_bigram_pair_... | [
"\n Creates a new statement matching the keyword arguments specified.\n Returns the created statement.\n "
] |
Please provide a description of the function:def create_many(self, statements):
create_statements = []
for statement in statements:
statement_data = statement.serialize()
tag_data = list(set(statement_data.pop('tags', [])))
statement_data['tags'] = tag_data
... | [
"\n Creates multiple statement entries.\n "
] |
Please provide a description of the function:def get_random(self):
from random import randint
count = self.count()
if count < 1:
raise self.EmptyDatabaseException()
random_integer = randint(0, count - 1)
statements = self.statements.find().limit(1).skip(r... | [
"\n Returns a random statement from the database\n "
] |
Please provide a description of the function:def add_tags(self, *tags):
self.tags.extend([
Tag(name=tag) for tag in tags
]) | [
"\n Add a list of strings to the statement as tags.\n "
] |
Please provide a description of the function:def get_preprocessed_statement(self, input_statement):
for preprocessor in self.chatbot.preprocessors:
input_statement = preprocessor(input_statement)
return input_statement | [
"\n Preprocess the input statement.\n "
] |
Please provide a description of the function:def export_for_training(self, file_path='./export.json'):
import json
export = {'conversations': self._generate_export_data()}
with open(file_path, 'w+') as jsonfile:
json.dump(export, jsonfile, ensure_ascii=False) | [
"\n Create a file from the database that can be used to\n train other chat bots.\n "
] |
Please provide a description of the function:def train(self, conversation):
previous_statement_text = None
previous_statement_search_text = ''
statements_to_create = []
for conversation_count, text in enumerate(conversation):
if self.show_training_progress:
... | [
"\n Train the chat bot based on the provided list of\n statements that represents a single conversation.\n "
] |
Please provide a description of the function:def is_downloaded(self, file_path):
if os.path.exists(file_path):
self.chatbot.logger.info('File is already downloaded')
return True
return False | [
"\n Check if the data file is already downloaded.\n "
] |
Please provide a description of the function:def is_extracted(self, file_path):
if os.path.isdir(file_path):
self.chatbot.logger.info('File is already extracted')
return True
return False | [
"\n Check if the data file is already extracted.\n "
] |
Please provide a description of the function:def download(self, url, show_status=True):
import requests
file_name = url.split('/')[-1]
file_path = os.path.join(self.data_directory, file_name)
# Do not download the data if it already exists
if self.is_downloaded(file_pa... | [
"\n Download a file from the given url.\n Show a progress indicator for the download status.\n Based on: http://stackoverflow.com/a/15645088/1547223\n "
] |
Please provide a description of the function:def extract(self, file_path):
import tarfile
print('Extracting {}'.format(file_path))
if not os.path.exists(self.extracted_data_directory):
os.makedirs(self.extracted_data_directory)
def track_progress(members):
... | [
"\n Extract a tar file at the specified file path.\n "
] |
Please provide a description of the function:def count(self):
Statement = self.get_model('statement')
session = self.Session()
statement_count = session.query(Statement).count()
session.close()
return statement_count | [
"\n Return the number of entries in the database.\n "
] |
Please provide a description of the function:def remove(self, statement_text):
Statement = self.get_model('statement')
session = self.Session()
query = session.query(Statement).filter_by(text=statement_text)
record = query.first()
session.delete(record)
self._... | [
"\n Removes the statement that matches the input text.\n Removes any responses from statements where the response text matches\n the input text.\n "
] |
Please provide a description of the function:def filter(self, **kwargs):
from sqlalchemy import or_
Statement = self.get_model('statement')
Tag = self.get_model('tag')
session = self.Session()
page_size = kwargs.pop('page_size', 1000)
order_by = kwargs.pop('or... | [
"\n Returns a list of objects from the database.\n The kwargs parameter can contain any number\n of attributes. Only objects which contain all\n listed attributes and in which all values match\n for all listed attributes will be returned.\n "
] |
Please provide a description of the function:def create(self, **kwargs):
Statement = self.get_model('statement')
Tag = self.get_model('tag')
session = self.Session()
tags = set(kwargs.pop('tags', []))
if 'search_text' not in kwargs:
kwargs['search_text'] =... | [
"\n Creates a new statement matching the keyword arguments specified.\n Returns the created statement.\n "
] |
Please provide a description of the function:def create_many(self, statements):
Statement = self.get_model('statement')
Tag = self.get_model('tag')
session = self.Session()
create_statements = []
create_tags = {}
for statement in statements:
state... | [
"\n Creates multiple statement entries.\n "
] |
Please provide a description of the function:def update(self, statement):
Statement = self.get_model('statement')
Tag = self.get_model('tag')
if statement is not None:
session = self.Session()
record = None
if hasattr(statement, 'id') and statement.... | [
"\n Modifies an entry in the database.\n Creates an entry if one does not exist.\n "
] |
Please provide a description of the function:def get_random(self):
import random
Statement = self.get_model('statement')
session = self.Session()
count = self.count()
if count < 1:
raise self.EmptyDatabaseException()
random_index = random.randrange... | [
"\n Returns a random statement from the database.\n "
] |
Please provide a description of the function:def drop(self):
Statement = self.get_model('statement')
Tag = self.get_model('tag')
session = self.Session()
session.query(Statement).delete()
session.query(Tag).delete()
session.commit()
session.close() | [
"\n Drop the database.\n "
] |
Please provide a description of the function:def create_database(self):
from chatterbot.ext.sqlalchemy_app.models import Base
Base.metadata.create_all(self.engine) | [
"\n Populate the database with the tables.\n "
] |
Please provide a description of the function:def post(self, request, *args, **kwargs):
input_data = json.loads(request.body.decode('utf-8'))
if 'text' not in input_data:
return JsonResponse({
'text': [
'The attribute "text" is required.'
... | [
"\n Return a response to the statement in the posted data.\n\n * The JSON data should contain a 'text' attribute.\n "
] |
Please provide a description of the function:def get_file_path(dotted_path, extension='json'):
# If the operating system's file path seperator character is in the string
if os.sep in dotted_path or '/' in dotted_path:
# Assume the path is a valid file path
return dotted_path
parts = do... | [
"\n Reads a dotted file path and returns the file path.\n "
] |
Please provide a description of the function:def read_corpus(file_name):
with io.open(file_name, encoding='utf-8') as data_file:
return yaml.load(data_file) | [
"\n Read and return the data from a corpus json file.\n "
] |
Please provide a description of the function:def list_corpus_files(dotted_path):
corpus_path = get_file_path(dotted_path, extension=CORPUS_EXTENSION)
paths = []
if os.path.isdir(corpus_path):
paths = glob.glob(corpus_path + '/**/*.' + CORPUS_EXTENSION, recursive=True)
else:
paths.a... | [
"\n Return a list of file paths to each data file in the specified corpus.\n "
] |
Please provide a description of the function:def load_corpus(*data_file_paths):
for file_path in data_file_paths:
corpus = []
corpus_data = read_corpus(file_path)
conversations = corpus_data.get('conversations', [])
corpus.extend(conversations)
categories = corpus_data... | [
"\n Return the data contained within a specified corpus.\n "
] |
Please provide a description of the function:def get_bigram_pair_string(self, text):
bigram_pairs = []
if len(text) <= 2:
text_without_punctuation = text.translate(self.punctuation_table)
if len(text_without_punctuation) >= 1:
text = text_without_punctua... | [
"\n Return a string of text containing part-of-speech, lemma pairs.\n "
] |
Please provide a description of the function:def filter(self, **kwargs):
from django.db.models import Q
Statement = self.get_model('statement')
kwargs.pop('page_size', 1000)
order_by = kwargs.pop('order_by', None)
tags = kwargs.pop('tags', [])
exclude_text = kw... | [
"\n Returns a list of statements in the database\n that match the parameters specified.\n "
] |
Please provide a description of the function:def create(self, **kwargs):
Statement = self.get_model('statement')
Tag = self.get_model('tag')
tags = kwargs.pop('tags', [])
if 'search_text' not in kwargs:
kwargs['search_text'] = self.tagger.get_bigram_pair_string(kwa... | [
"\n Creates a new statement matching the keyword arguments specified.\n Returns the created statement.\n "
] |
Please provide a description of the function:def create_many(self, statements):
Statement = self.get_model('statement')
Tag = self.get_model('tag')
tag_cache = {}
for statement in statements:
statement_data = statement.serialize()
tag_data = statement_... | [
"\n Creates multiple statement entries.\n "
] |
Please provide a description of the function:def update(self, statement):
Statement = self.get_model('statement')
Tag = self.get_model('tag')
if hasattr(statement, 'id'):
statement.save()
else:
statement = Statement.objects.create(
text=s... | [
"\n Update the provided statement.\n "
] |
Please provide a description of the function:def get_random(self):
Statement = self.get_model('statement')
statement = Statement.objects.order_by('?').first()
if statement is None:
raise self.EmptyDatabaseException()
return statement | [
"\n Returns a random statement from the database\n "
] |
Please provide a description of the function:def remove(self, statement_text):
Statement = self.get_model('statement')
statements = Statement.objects.filter(text=statement_text)
statements.delete() | [
"\n Removes the statement that matches the input text.\n Removes any responses from statements if the response text matches the\n input text.\n "
] |
Please provide a description of the function:def drop(self):
Statement = self.get_model('statement')
Tag = self.get_model('tag')
Statement.objects.all().delete()
Tag.objects.all().delete() | [
"\n Remove all data from the database.\n "
] |
Please provide a description of the function:def clean_whitespace(statement):
import re
# Replace linebreaks and tabs with spaces
statement.text = statement.text.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ')
# Remove any leeding or trailing whitespace
statement.text = statement.tex... | [
"\n Remove any consecutive whitespace characters from the statement text.\n "
] |
Please provide a description of the function:def unescape_html(statement):
import html
statement.text = html.unescape(statement.text)
return statement | [
"\n Convert escaped html characters into unescaped html characters.\n For example: \"<b>\" becomes \"<b>\".\n "
] |
Please provide a description of the function:def convert_to_ascii(statement):
import unicodedata
text = unicodedata.normalize('NFKD', statement.text)
text = text.encode('ascii', 'ignore').decode('utf-8')
statement.text = str(text)
return statement | [
"\n Converts unicode characters to ASCII character equivalents.\n For example: \"på fédéral\" becomes \"pa federal\".\n "
] |
Please provide a description of the function:def convert_string_to_number(value):
if value is None:
return 1
if isinstance(value, int):
return value
if value.isdigit():
return int(value)
num_list = map(lambda s: NUMBERS[s], re.findall(numbers + '+', value.lower()))
retur... | [
"\n Convert strings to numbers\n "
] |
Please provide a description of the function:def convert_time_to_hour_minute(hour, minute, convention):
if hour is None:
hour = 0
if minute is None:
minute = 0
if convention is None:
convention = 'am'
hour = int(hour)
minute = int(minute)
if convention.lower() == '... | [
"\n Convert time to hour, minute\n "
] |
Please provide a description of the function:def date_from_quarter(base_date, ordinal, year):
interval = 3
month_start = interval * (ordinal - 1)
if month_start < 0:
month_start = 9
month_end = month_start + interval
if month_start == 0:
month_start = 1
return [
date... | [
"\n Extract date from quarter of a year\n "
] |
Please provide a description of the function:def date_from_relative_day(base_date, time, dow):
# Reset date to start of the day
base_date = datetime(base_date.year, base_date.month, base_date.day)
time = time.lower()
dow = dow.lower()
if time == 'this' or time == 'coming':
# Else day of... | [
"\n Converts relative day to time\n Ex: this tuesday, last tuesday\n "
] |
Please provide a description of the function:def date_from_relative_week_year(base_date, time, dow, ordinal=1):
# If there is an ordinal (next 3 weeks) => return a start and end range
# Reset date to start of the day
relative_date = datetime(base_date.year, base_date.month, base_date.day)
ord = con... | [
"\n Converts relative day to time\n Eg. this tuesday, last tuesday\n "
] |
Please provide a description of the function:def date_from_adverb(base_date, name):
# Reset date to start of the day
adverb_date = datetime(base_date.year, base_date.month, base_date.day)
if name == 'today' or name == 'tonite' or name == 'tonight':
return adverb_date.today()
elif name == 'y... | [
"\n Convert Day adverbs to dates\n Tomorrow => Date\n Today => Date\n "
] |
Please provide a description of the function:def date_from_duration(base_date, number_as_string, unit, duration, base_time=None):
# Check if query is `2 days before yesterday` or `day before yesterday`
if base_time is not None:
base_date = date_from_adverb(base_date, base_time)
num = convert_st... | [
"\n Find dates from duration\n Eg: 20 days from now\n Currently does not support strings like \"20 days from last monday\".\n "
] |
Please provide a description of the function:def this_week_day(base_date, weekday):
day_of_week = base_date.weekday()
# If today is Tuesday and the query is `this monday`
# We should output the next_week monday
if day_of_week > weekday:
return next_week_day(base_date, weekday)
start_of_... | [
"\n Finds coming weekday\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.