code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
async def clear(self): """Close all free connections in pool.""" async with self._cond: while self._free: conn = self._free.popleft() await conn.ensure_closed() self._cond.notify()
Close all free connections in pool.
clear
python
aio-libs/aiomysql
aiomysql/pool.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py
MIT
def close(self): """Close pool. Mark all pool connections to be closed on getting back to pool. Closed pool doesn't allow to acquire new connections. """ if self._closed: return self._closing = True
Close pool. Mark all pool connections to be closed on getting back to pool. Closed pool doesn't allow to acquire new connections.
close
python
aio-libs/aiomysql
aiomysql/pool.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py
MIT
def terminate(self): """Terminate pool. Close pool with instantly closing all acquired connections also. """ self.close() for conn in list(self._used): conn.close() self._terminated.add(conn) self._used.clear()
Terminate pool. Close pool with instantly closing all acquired connections also.
terminate
python
aio-libs/aiomysql
aiomysql/pool.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py
MIT
async def wait_closed(self): """Wait for closing all pool's connections.""" if self._closed: return if not self._closing: raise RuntimeError(".wait_closed() should be called " "after .close()") while self._free: conn = ...
Wait for closing all pool's connections.
wait_closed
python
aio-libs/aiomysql
aiomysql/pool.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py
MIT
def acquire(self): """Acquire free connection from the pool.""" coro = self._acquire() return _PoolAcquireContextManager(coro, self)
Acquire free connection from the pool.
acquire
python
aio-libs/aiomysql
aiomysql/pool.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py
MIT
def release(self, conn): """Release free connection back to the connection pool. This is **NOT** a coroutine. """ fut = self._loop.create_future() fut.set_result(None) if conn in self._terminated: assert conn.closed, conn self._terminated.remove(...
Release free connection back to the connection pool. This is **NOT** a coroutine.
release
python
aio-libs/aiomysql
aiomysql/pool.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/pool.py
MIT
async def scalar(self, query, *multiparams, **params): """Executes a SQL query and returns a scalar value.""" res = await self.execute(query, *multiparams, **params) return (await res.scalar())
Executes a SQL query and returns a scalar value.
scalar
python
aio-libs/aiomysql
aiomysql/sa/connection.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/connection.py
MIT
async def begin_twophase(self, xid=None): """Begin a two-phase or XA transaction and return a transaction handle. The returned object is an instance of TwoPhaseTransaction, which in addition to the methods provided by Transaction, also provides a TwoPhaseTransaction.prep...
Begin a two-phase or XA transaction and return a transaction handle. The returned object is an instance of TwoPhaseTransaction, which in addition to the methods provided by Transaction, also provides a TwoPhaseTransaction.prepare() method. xid - the two phase transactio...
begin_twophase
python
aio-libs/aiomysql
aiomysql/sa/connection.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/connection.py
MIT
async def recover_twophase(self): """Return a list of prepared twophase transaction ids.""" result = await self.execute("XA RECOVER;") return [row[0] for row in result]
Return a list of prepared twophase transaction ids.
recover_twophase
python
aio-libs/aiomysql
aiomysql/sa/connection.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/connection.py
MIT
async def close(self): """Close this SAConnection. This results in a release of the underlying database resources, that is, the underlying connection referenced internally. The underlying connection is typically restored back to the connection-holding Pool referenced by the Engi...
Close this SAConnection. This results in a release of the underlying database resources, that is, the underlying connection referenced internally. The underlying connection is typically restored back to the connection-holding Pool referenced by the Engine that produced this SACo...
close
python
aio-libs/aiomysql
aiomysql/sa/connection.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/connection.py
MIT
def _distill_params(multiparams, params): """Given arguments from the calling form *multiparams, **params, return a list of bind parameter structures, usually a list of dictionaries. In the case of 'raw' execution which accepts positional parameters, it may be a list of tuples or lists. """ ...
Given arguments from the calling form *multiparams, **params, return a list of bind parameter structures, usually a list of dictionaries. In the case of 'raw' execution which accepts positional parameters, it may be a list of tuples or lists.
_distill_params
python
aio-libs/aiomysql
aiomysql/sa/connection.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/connection.py
MIT
def create_engine(minsize=1, maxsize=10, loop=None, dialect=_dialect, pool_recycle=-1, compiled_cache=None, **kwargs): """A coroutine for Engine creation. Returns Engine instance with embedded connection pool. The pool has *minsize* opened connections to MySQL server. ...
A coroutine for Engine creation. Returns Engine instance with embedded connection pool. The pool has *minsize* opened connections to MySQL server.
create_engine
python
aio-libs/aiomysql
aiomysql/sa/engine.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/engine.py
MIT
async def wait_closed(self): """Wait for closing all engine's connections.""" await self._pool.wait_closed()
Wait for closing all engine's connections.
wait_closed
python
aio-libs/aiomysql
aiomysql/sa/engine.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/engine.py
MIT
def __init__(self, result_proxy, row, processors, keymap): """RowProxy objects are constructed by ResultProxy objects.""" self._result_proxy = result_proxy self._row = row self._processors = processors self._keymap = keymap
RowProxy objects are constructed by ResultProxy objects.
__init__
python
aio-libs/aiomysql
aiomysql/sa/result.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py
MIT
def keys(self): """Return the current set of string keys for rows.""" if self._metadata: return tuple(self._metadata.keys) else: return ()
Return the current set of string keys for rows.
keys
python
aio-libs/aiomysql
aiomysql/sa/result.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py
MIT
async def close(self): """Close this ResultProxy. Closes the underlying DBAPI cursor corresponding to the execution. Note that any data cached within this ResultProxy is still available. For some types of results, this may include buffered rows. If this ResultProxy was generat...
Close this ResultProxy. Closes the underlying DBAPI cursor corresponding to the execution. Note that any data cached within this ResultProxy is still available. For some types of results, this may include buffered rows. If this ResultProxy was generated from an implicit execution, ...
close
python
aio-libs/aiomysql
aiomysql/sa/result.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py
MIT
async def fetchall(self): """Fetch all rows, just like DB-API cursor.fetchall().""" try: rows = await self._cursor.fetchall() except AttributeError: self._non_result() else: ret = self._process_rows(rows) await self.close() retu...
Fetch all rows, just like DB-API cursor.fetchall().
fetchall
python
aio-libs/aiomysql
aiomysql/sa/result.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py
MIT
async def fetchone(self): """Fetch one row, just like DB-API cursor.fetchone(). If a row is present, the cursor remains open after this is called. Else the cursor is automatically closed and None is returned. """ try: row = await self._cursor.fetchone() excep...
Fetch one row, just like DB-API cursor.fetchone(). If a row is present, the cursor remains open after this is called. Else the cursor is automatically closed and None is returned.
fetchone
python
aio-libs/aiomysql
aiomysql/sa/result.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py
MIT
async def fetchmany(self, size=None): """Fetch many rows, just like DB-API cursor.fetchmany(size=cursor.arraysize). If rows are present, the cursor remains open after this is called. Else the cursor is automatically closed and an empty list is returned. """ try: ...
Fetch many rows, just like DB-API cursor.fetchmany(size=cursor.arraysize). If rows are present, the cursor remains open after this is called. Else the cursor is automatically closed and an empty list is returned.
fetchmany
python
aio-libs/aiomysql
aiomysql/sa/result.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py
MIT
async def first(self): """Fetch the first row and then close the result set unconditionally. Returns None if no row is present. """ if self._metadata is None: self._non_result() try: return (await self.fetchone()) finally: await self.c...
Fetch the first row and then close the result set unconditionally. Returns None if no row is present.
first
python
aio-libs/aiomysql
aiomysql/sa/result.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py
MIT
async def scalar(self): """Fetch the first column of the first row, and close the result set. Returns None if no row is present. """ row = await self.first() if row is not None: return row[0] else: return None
Fetch the first column of the first row, and close the result set. Returns None if no row is present.
scalar
python
aio-libs/aiomysql
aiomysql/sa/result.py
https://github.com/aio-libs/aiomysql/blob/master/aiomysql/sa/result.py
MIT
def pytest_pyfunc_call(pyfuncitem): """ Run asyncio marked test functions in an event loop instead of a normal function call. """ if 'run_loop' in pyfuncitem.keywords: funcargs = pyfuncitem.funcargs loop = funcargs['loop'] testargs = {arg: funcargs[arg] fo...
Run asyncio marked test functions in an event loop instead of a normal function call.
pytest_pyfunc_call
python
aio-libs/aiomysql
tests/conftest.py
https://github.com/aio-libs/aiomysql/blob/master/tests/conftest.py
MIT
def mysql_server_is(server_version, version_tuple): """Return True if the given connection is on the version given or greater. e.g.:: if self.mysql_server_is(conn, (5, 6, 4)): # do something for MySQL 5.6.4 and above """ server_version_tuple = tuple( (int(dig) if dig is n...
Return True if the given connection is on the version given or greater. e.g.:: if self.mysql_server_is(conn, (5, 6, 4)): # do something for MySQL 5.6.4 and above
mysql_server_is
python
aio-libs/aiomysql
tests/test_basic.py
https://github.com/aio-libs/aiomysql/blob/master/tests/test_basic.py
MIT
async def test_issue_8(connection): """ Primary Key and Index error when selecting data """ conn = connection c = await conn.cursor() await c.execute("drop table if exists test") await c.execute("""CREATE TABLE `test` ( `station` int(10) NOT NULL DEFAULT '0', `dh` datetime NOT NULL D...
Primary Key and Index error when selecting data
test_issue_8
python
aio-libs/aiomysql
tests/test_issues.py
https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py
MIT
async def test_issue_15(connection): """ query should be expanded before perform character encoding """ conn = connection c = await conn.cursor() await c.execute("drop table if exists issue15") await c.execute("create table issue15 (t varchar(32))") try: await c.execute("insert into issu...
query should be expanded before perform character encoding
test_issue_15
python
aio-libs/aiomysql
tests/test_issues.py
https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py
MIT
async def test_issue_16(connection): """ Patch for string and tuple escaping """ conn = connection c = await conn.cursor() await c.execute("drop table if exists issue16") await c.execute("create table issue16 (name varchar(32) " "primary key, email varchar(32))") try: ...
Patch for string and tuple escaping
test_issue_16
python
aio-libs/aiomysql
tests/test_issues.py
https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py
MIT
async def test_issue_17(connection, connection_creator, mysql_params): """ could not connect mysql use passwod """ conn = connection c = await conn.cursor() db = mysql_params['db'] # grant access to a table to a user with a password try: await c.execute("drop table if exists issue17") ...
could not connect mysql use passwod
test_issue_17
python
aio-libs/aiomysql
tests/test_issues.py
https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py
MIT
async def test_issue_79(connection): """ Duplicate field overwrites the previous one in the result of DictCursor """ conn = connection c = await conn.cursor(aiomysql.cursors.DictCursor) await c.execute("drop table if exists a") await c.execute("drop table if exists b") await c.execute("""CR...
Duplicate field overwrites the previous one in the result of DictCursor
test_issue_79
python
aio-libs/aiomysql
tests/test_issues.py
https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py
MIT
async def test_issue_95(connection): """ Leftover trailing OK packet for "CALL my_sp" queries """ conn = connection cur = await conn.cursor() await cur.execute("DROP PROCEDURE IF EXISTS `foo`") await cur.execute("""CREATE PROCEDURE `foo` () BEGIN SELECT 1; END""") try: aw...
Leftover trailing OK packet for "CALL my_sp" queries
test_issue_95
python
aio-libs/aiomysql
tests/test_issues.py
https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py
MIT
async def test_issue_175(connection): """ The number of fields returned by server is read in wrong way """ conn = connection cur = await conn.cursor() for length in (200, 300): cols = ', '.join(f'c{i} integer' for i in range(length)) sql = f'create table test_field_count ({cols})' ...
The number of fields returned by server is read in wrong way
test_issue_175
python
aio-libs/aiomysql
tests/test_issues.py
https://github.com/aio-libs/aiomysql/blob/master/tests/test_issues.py
MIT
def lstm(inputs, hparams, train, name, initial_state=None): '''Run LSTM cell on inputs, assuming they are [batch x time x size].''' def dropout_lstm_cell(): return tf.contrib.rnn.DropoutWrapper( tf.contrib.cudnn_rnn.CudnnCompatibleLSTMCell(hparams.hidden_size), input_keep_prob=1.0 - hparams.dro...
Run LSTM cell on inputs, assuming they are [batch x time x size].
lstm
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/models/gradient_checkpointed_seq2seq.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/models/gradient_checkpointed_seq2seq.py
MIT
def lstm_seq2seq_internal_dynamic(inputs, targets, hparams, train): '''The basic LSTM seq2seq model, main step used for training.''' with tf.variable_scope('lstm_seq2seq'): if inputs is not None: # Flatten inputs. inputs = common_layers.flatten4d3d(inputs) # LSTM encoder. _, final_encode...
The basic LSTM seq2seq model, main step used for training.
lstm_seq2seq_internal_dynamic
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/models/gradient_checkpointed_seq2seq.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/models/gradient_checkpointed_seq2seq.py
MIT
def lstm_seq2seq_internal_static(inputs, targets, hparams, train): '''The basic LSTM seq2seq model, main step used for training.''' with tf.variable_scope('lstm_seq2seq'): if inputs is not None: # Flatten inputs. inputs = tf.reverse(common_layers.flatten4d3d(inputs), axis=[1]) # Construct sta...
The basic LSTM seq2seq model, main step used for training.
lstm_seq2seq_internal_static
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/models/gradient_checkpointed_seq2seq.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/models/gradient_checkpointed_seq2seq.py
MIT
def generator(self, data_dir, tmp_dir, train): ''' Generate the vocab and then build train and validation t2t-datagen files. Four .txt files have to be present in the data_dir directory: trainSource.txt trainTarget.txt devSource.txt devTarget.txt Params: :train: Whether we...
Generate the vocab and then build train and validation t2t-datagen files. Four .txt files have to be present in the data_dir directory: trainSource.txt trainTarget.txt devSource.txt devTarget.txt Params: :train: Whether we are in train mode or not.
generator
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/character_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/character_chatbot.py
MIT
def preprocess_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' # Set the raw data directory and data. self.raw_data_dir = os.path.join('/'.join(self._data_dir.split('/')[:-1]), 'raw_data') self.raw_data = os.pa...
Params: :train_mode: Whether we are in train or dev mode.
preprocess_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/cornell_chatbots.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/cornell_chatbots.py
MIT
def create_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' # Open the 6 files. trainSource, trainTarget, devSource, devTarget, testSource, testTarget = \ self.open_6_files() # Open the raw data. movie_lines = open( os.path.joi...
Params: :train_mode: Whether we are in train or dev mode.
create_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/cornell_chatbots.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/cornell_chatbots.py
MIT
def clean_line(self, line): ''' Params: :line: Line to be processed and returned. ''' # 2 functions for more complex replacing. def replace(matchobj): return re.sub("'", " '", str(matchobj.group(0))) def replace_null(matchobj): return re.sub("'", '', str(matchobj.group(0))) ...
Params: :line: Line to be processed and returned.
clean_line
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/cornell_chatbots.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/cornell_chatbots.py
MIT
def create_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' # Open the 6 files. trainSource, trainTarget, devSource, devTarget, testSource, testTarget = \ self.open_6_files() # Open the raw data. movie_lines = open( os.path.joi...
Params: :train_mode: Whether we are in train or dev mode.
create_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/cornell_chatbots.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/cornell_chatbots.py
MIT
def replace_names(self, line_dict, name_vocab): ''' Params: :line_dict: Dictionary containing all the parsed lines. :name_vocab: The vocabulary of names. ''' name_list = [] for name, _ in name_vocab.most_common(self.targeted_name_vocab_size - 1): name_list.append(name) for...
Params: :line_dict: Dictionary containing all the parsed lines. :name_vocab: The vocabulary of names.
replace_names
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/cornell_chatbots.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/cornell_chatbots.py
MIT
def save_vocab(self, vocab, name_vocab): ''' Params: :vocab: Vocabulary list. :name_vocab: Name vocabulary. ''' voc_file = open(os.path.join(self._data_dir, self.vocab_file), 'w') # put the reserved tokens in voc_file.write('<pad>\n') voc_file.write('<EOS>\n') # basi...
Params: :vocab: Vocabulary list. :name_vocab: Name vocabulary.
save_vocab
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/cornell_chatbots.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/cornell_chatbots.py
MIT
def preprocess_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' # Set the raw data directory and data. self.raw_data_dir = os.path.join('/'.join(self._data_dir.split('/')[:-1]), 'raw_data') self.raw_data = os.pa...
Params: :train_mode: Whether we are in train or dev mode.
preprocess_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/daily_dialog_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/daily_dialog_chatbot.py
MIT
def create_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' # Open the 6 files. trainSource, trainTarget, devSource, devTarget, testSource, testTarget = \ self.open_6_files() # Open the raw data. dialogs = open( os.path.join(se...
Params: :train_mode: Whether we are in train or dev mode.
create_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/daily_dialog_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/daily_dialog_chatbot.py
MIT
def preprocess_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' year = '' if self.dataset_version == 2009 else str(self.dataset_version) # Set the raw data directory and data. self.raw_data_dir = os.path.join('/'.join(self._data_dir.split('/')[:-1]...
Params: :train_mode: Whether we are in train or dev mode.
preprocess_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/opensubtitles_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/opensubtitles_chatbot.py
MIT
def data_pipeline_status(self, train_mode): ''' This function first check recursively at which point in the data processing point are we (what files can be found on the disk), and then proceeds from there. Params: :train_mode: Whether we are in train or dev mode. ''' # Build the sour...
This function first check recursively at which point in the data processing point are we (what files can be found on the disk), and then proceeds from there. Params: :train_mode: Whether we are in train or dev mode.
data_pipeline_status
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/opensubtitles_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/opensubtitles_chatbot.py
MIT
def download_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' # Open the url and download the data with progress bars. data_stream = requests.get(self._url, stream=True) with open(self._zipped_data, 'wb') as file: total_length = int(data_str...
Params: :train_mode: Whether we are in train or dev mode.
download_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/opensubtitles_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/opensubtitles_chatbot.py
MIT
def extract_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' if self._zipped_data[-2:] == 'gz': zip_file = tarfile.open(self._zipped_data, 'r:gz') elif self._zipped_data[-3:] == 'zip': zip_file = zipfile.ZipFile(self._zipped_data, 'r') ...
Params: :train_mode: Whether we are in train or dev mode.
extract_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/opensubtitles_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/opensubtitles_chatbot.py
MIT
def create_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' # open the 6 files trainSource, trainTarget, devSource, devTarget, testSource, testTarget = \ self.open_6_files() conv_id = 0 number_of_lines = 0 dataset_split_counter = 0...
Params: :train_mode: Whether we are in train or dev mode.
create_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/opensubtitles_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/opensubtitles_chatbot.py
MIT
def clean_line(self, line): ''' Params: :line: Line to be processed and returned. ''' line = line.lower() line = re.sub(' \' ', '\'', line) line = unicodedata.normalize('NFKD', line) # Keep some special tokens. line = re.sub('[^a-z .?!\'0-9]', '', line) line = re.sub('n \'t', ...
Params: :line: Line to be processed and returned.
clean_line
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/opensubtitles_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/opensubtitles_chatbot.py
MIT
def preprocess_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' # Set the raw data directory and data. self.raw_data_dir = os.path.join('/'.join(self._data_dir.split('/')[:-1]), 'raw_data') self.raw_data = os.pa...
Params: :train_mode: Whether we are in train or dev mode.
preprocess_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/persona_chat_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/persona_chat_chatbot.py
MIT
def extract_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' if self._zipped_data[-2:] == 'gz': zip_file = tarfile.open(self._zipped_data, 'r:gz') elif self._zipped_data[-3:] == 'zip': zip_file = zipfile.ZipFile(self._zipped_data, 'r') ...
Params: :train_mode: Whether we are in train or dev mode.
extract_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/persona_chat_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/persona_chat_chatbot.py
MIT
def create_data(self, train_mode): ''' Params: :train_mode: Whether we are in train or dev mode. ''' # Open the 6 files. trainSource, trainTarget, devSource, devTarget, testSource, testTarget = \ self.open_6_files() # Open the raw data. train_dialogs = open( os.path.j...
Params: :train_mode: Whether we are in train or dev mode.
create_data
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/persona_chat_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/persona_chat_chatbot.py
MIT
def generate_samples(self, data_dir, tmp_dir, data_split): ''' The function assumes that if you have data at one level of the pipeline, you don't want to re-generate it, so for example if the 4 txt files exist, the function continues by generating the t2t-datagen format files. So if you want to re-d...
The function assumes that if you have data at one level of the pipeline, you don't want to re-generate it, so for example if the 4 txt files exist, the function continues by generating the t2t-datagen format files. So if you want to re-download or re-generate data, you have to delete it first from ...
generate_samples
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/problems/word_chatbot.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/problems/word_chatbot.py
MIT
def compute_gradients(self, loss, var_list=None, gate_gradients=tf.train.Optimizer.GATE_OP, aggregation_method=None, colocate_gradients_with_ops=False, grad_loss=None): '''Compute gradients of `loss` for the variables in...
Compute gradients of `loss` for the variables in `var_list`. This is the first part of `minimize()`. It returns a list of (gradient, variable) pairs where 'gradient' is the gradient for 'variable'. Note that 'gradient' can be a `Tensor`, an `IndexedSlices`, or `None` if there is no gradient for the ...
compute_gradients
python
ricsinaruto/Seq2seqChatbots
t2t_csaky/utils/optimizer.py
https://github.com/ricsinaruto/Seq2seqChatbots/blob/master/t2t_csaky/utils/optimizer.py
MIT
def create_app(path=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=False, api_url=None, title=None, text=None, autorefresh=None, quiet=None, theme='light', grip_class=None): """ Creates a G...
Creates a Grip application with the specified overrides.
create_app
python
joeyespo/grip
grip/api.py
https://github.com/joeyespo/grip/blob/master/grip/api.py
MIT
def serve(path=None, host=None, port=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=False, api_url=None, title=None, autorefresh=True, browser=False, quiet=None, theme='light', grip_class=None): """ Start...
Starts a server to render the specified file or directory containing a README.
serve
python
joeyespo/grip
grip/api.py
https://github.com/joeyespo/grip/blob/master/grip/api.py
MIT
def clear_cache(grip_class=None): """ Clears the cached styles and assets. """ if grip_class is None: grip_class = Grip grip_class(StdinReader()).clear_cache()
Clears the cached styles and assets.
clear_cache
python
joeyespo/grip
grip/api.py
https://github.com/joeyespo/grip/blob/master/grip/api.py
MIT
def render_page(path=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=False, api_url=None, title=None, text=None, quiet=None, theme='light', grip_class=None): """ Renders t...
Renders the specified markup text to an HTML page and returns it.
render_page
python
joeyespo/grip
grip/api.py
https://github.com/joeyespo/grip/blob/master/grip/api.py
MIT
def render_content(text, user_content=False, context=None, username=None, password=None, render_offline=False, api_url=None): """ Renders the specified markup and returns the result. """ renderer = (GitHubRenderer(user_content, context, api_url) if not render_offline e...
Renders the specified markup and returns the result.
render_content
python
joeyespo/grip
grip/api.py
https://github.com/joeyespo/grip/blob/master/grip/api.py
MIT
def export(path=None, user_content=False, context=None, username=None, password=None, render_offline=False, render_wide=False, render_inline=True, out_filename=None, api_url=None, title=None, quiet=False, theme='light', grip_class=None): """ Exports the rendered HTML to a file. ...
Exports the rendered HTML to a file.
export
python
joeyespo/grip
grip/api.py
https://github.com/joeyespo/grip/blob/master/grip/api.py
MIT
def _get_styles(self, style_urls, asset_url_path): """ Gets the content of the given list of style URLs and inlines assets. """ styles = [] for style_url in style_urls: urls_inline = STYLE_ASSET_URLS_INLINE_FORMAT.format( asset_url_path.rstrip(...
Gets the content of the given list of style URLs and inlines assets.
_get_styles
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def _inline_styles(self): """ Downloads the assets from the style URL list, clears it, and adds each style with its embedded asset to the literal style list. """ styles = self._get_styles(self.assets.style_urls, url_for('asset')) self.assets.styles.extend(styles) ...
Downloads the assets from the style URL list, clears it, and adds each style with its embedded asset to the literal style list.
_inline_styles
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def _retrieve_styles(self): """ Retrieves the style URLs from the source and caches them. This is called before the first request is dispatched. """ if self._styles_retrieved: return self._styles_retrieved = True try: self.assets.retrieve_...
Retrieves the style URLs from the source and caches them. This is called before the first request is dispatched.
_retrieve_styles
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def default_asset_manager(self): """ Returns the default asset manager using the current config. This is only used if asset_manager is set to None in the constructor. """ cache_path = None cache_directory = self.config['CACHE_DIRECTORY'] if cache_directory: ...
Returns the default asset manager using the current config. This is only used if asset_manager is set to None in the constructor.
default_asset_manager
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def render(self, route=None): """ Renders the application and returns the HTML unicode that would normally appear when visiting in the browser. """ if route is None: route = '/' with self.test_client() as c: response = c.get(route, follow_redirects...
Renders the application and returns the HTML unicode that would normally appear when visiting in the browser.
render
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def run(self, host=None, port=None, debug=None, use_reloader=None, open_browser=False): """ Starts a server to render the README. """ if host is None: host = self.config['HOST'] if port is None: port = self.config['PORT'] if debug is No...
Starts a server to render the README.
run
python
joeyespo/grip
grip/app.py
https://github.com/joeyespo/grip/blob/master/grip/app.py
MIT
def cache_filename(self, url): """ Gets a suitable relative filename for the specified URL. """ # FUTURE: Use url exactly instead of flattening it here url = posixpath.basename(url) return self._strip_url_params(url)
Gets a suitable relative filename for the specified URL.
cache_filename
python
joeyespo/grip
grip/assets.py
https://github.com/joeyespo/grip/blob/master/grip/assets.py
MIT
def _get_style_urls(self, asset_url_path): """ Gets the specified resource and parses all style URLs and their assets in the form of the specified patterns. """ # Check cache if self.cache_path: cached = self._get_cached_style_urls(asset_url_path) ...
Gets the specified resource and parses all style URLs and their assets in the form of the specified patterns.
_get_style_urls
python
joeyespo/grip
grip/assets.py
https://github.com/joeyespo/grip/blob/master/grip/assets.py
MIT
def _get_cached_style_urls(self, asset_url_path): """ Gets the URLs of the cached styles. """ try: cached_styles = os.listdir(self.cache_path) except IOError as ex: if ex.errno != errno.ENOENT and ex.errno != errno.ESRCH: raise ...
Gets the URLs of the cached styles.
_get_cached_style_urls
python
joeyespo/grip
grip/assets.py
https://github.com/joeyespo/grip/blob/master/grip/assets.py
MIT
def _cache_contents(self, style_urls, asset_url_path): """ Fetches the given URLs and caches their contents and their assets in the given directory. """ files = {} asset_urls = [] for style_url in style_urls: if not self.quiet: print('...
Fetches the given URLs and caches their contents and their assets in the given directory.
_cache_contents
python
joeyespo/grip
grip/assets.py
https://github.com/joeyespo/grip/blob/master/grip/assets.py
MIT
def retrieve_styles(self, asset_url_path): """ Get style URLs from the source HTML page and specified cached asset base URL. """ if not asset_url_path.endswith('/'): asset_url_path += '/' self.style_urls.extend(self._get_style_urls(asset_url_path))
Get style URLs from the source HTML page and specified cached asset base URL.
retrieve_styles
python
joeyespo/grip
grip/assets.py
https://github.com/joeyespo/grip/blob/master/grip/assets.py
MIT
def is_server_running(host, port): """ Checks whether a server is currently listening on the specified host and port. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: return s.connect_ex((host, port)) == 0 finally: s.close()
Checks whether a server is currently listening on the specified host and port.
is_server_running
python
joeyespo/grip
grip/browser.py
https://github.com/joeyespo/grip/blob/master/grip/browser.py
MIT
def wait_for_server(host, port, cancel_event=None): """ Blocks until a local server is listening on the specified host and port. Set cancel_event to cancel the wait. This is intended to be used in conjunction with running the Flask server. """ while not is_server_running(host, port): ...
Blocks until a local server is listening on the specified host and port. Set cancel_event to cancel the wait. This is intended to be used in conjunction with running the Flask server.
wait_for_server
python
joeyespo/grip
grip/browser.py
https://github.com/joeyespo/grip/blob/master/grip/browser.py
MIT
def start_browser(url): """ Opens the specified URL in a new browser window. """ try: webbrowser.open(url) except Exception: pass
Opens the specified URL in a new browser window.
start_browser
python
joeyespo/grip
grip/browser.py
https://github.com/joeyespo/grip/blob/master/grip/browser.py
MIT
def wait_and_start_browser(host, port=None, cancel_event=None): """ Waits for the server to run and then opens the specified address in the browser. Set cancel_event to cancel the wait. """ if host == '0.0.0.0': host = 'localhost' if port is None: port = 80 if wait_for_serve...
Waits for the server to run and then opens the specified address in the browser. Set cancel_event to cancel the wait.
wait_and_start_browser
python
joeyespo/grip
grip/browser.py
https://github.com/joeyespo/grip/blob/master/grip/browser.py
MIT
def start_browser_when_ready(host, port=None, cancel_event=None): """ Starts a thread that waits for the server then opens the specified address in the browser. Set cancel_event to cancel the wait. The started thread object is returned. """ browser_thread = Thread( target=wait_and_start_...
Starts a thread that waits for the server then opens the specified address in the browser. Set cancel_event to cancel the wait. The started thread object is returned.
start_browser_when_ready
python
joeyespo/grip
grip/browser.py
https://github.com/joeyespo/grip/blob/master/grip/browser.py
MIT
def main(argv=None, force_utf8=True, patch_svg=True): """ The entry point of the application. """ if force_utf8 and sys.version_info[0] == 2: reload(sys) # noqa sys.setdefaultencoding('utf-8') if patch_svg and sys.version_info[0] == 2 and sys.version_info[1] <= 6: mimetypes....
The entry point of the application.
main
python
joeyespo/grip
grip/command.py
https://github.com/joeyespo/grip/blob/master/grip/command.py
MIT
def patch(html, user_content=False): """ Processes the HTML rendered by the GitHub API, patching any inconsistencies from the main site. """ # FUTURE: Remove this once GitHub API renders task lists # https://github.com/isaacs/github/issues/309 if not user_content: html = INCOMPLETE_T...
Processes the HTML rendered by the GitHub API, patching any inconsistencies from the main site.
patch
python
joeyespo/grip
grip/patcher.py
https://github.com/joeyespo/grip/blob/master/grip/patcher.py
MIT
def normalize_subpath(self, subpath): """ Returns the normalized subpath. This allows Readme files to be inferred from directories while still allowing relative paths to work properly. Override to change the default behavior of returning the specified subpath as-is. ...
Returns the normalized subpath. This allows Readme files to be inferred from directories while still allowing relative paths to work properly. Override to change the default behavior of returning the specified subpath as-is.
normalize_subpath
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def mimetype_for(self, subpath=None): """ Gets the mimetype for the specified subpath. """ if subpath is None: subpath = DEFAULT_FILENAME mimetype, _ = mimetypes.guess_type(subpath) return mimetype
Gets the mimetype for the specified subpath.
mimetype_for
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def _find_file(self, path, silent=False): """ Gets the full path and extension, or None if a README file could not be found at the specified path. """ for filename in DEFAULT_FILENAMES: full_path = os.path.join(path, filename) if path else filename if os.p...
Gets the full path and extension, or None if a README file could not be found at the specified path.
_find_file
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def _resolve_readme(self, path=None, silent=False): """ Returns the path if it's a file; otherwise, looks for a compatible README file in the directory specified by path. If path is None, the current working directory is used. If silent is set, the default relative filename wil...
Returns the path if it's a file; otherwise, looks for a compatible README file in the directory specified by path. If path is None, the current working directory is used. If silent is set, the default relative filename will be returned if path is a directory or None if it does...
_resolve_readme
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def normalize_subpath(self, subpath): """ Normalizes the specified subpath, or None if subpath is None. This allows Readme files to be inferred from directories while still allowing relative paths to work properly. Raises werkzeug.exceptions.NotFound if the resulting path ...
Normalizes the specified subpath, or None if subpath is None. This allows Readme files to be inferred from directories while still allowing relative paths to work properly. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of the root directory.
normalize_subpath
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def readme_for(self, subpath): """ Returns the full path for the README file for the specified subpath, or the root filename if subpath is None. Raises ReadmeNotFoundError if a README for the specified subpath does not exist. Raises werkzeug.exceptions.NotFound if the r...
Returns the full path for the README file for the specified subpath, or the root filename if subpath is None. Raises ReadmeNotFoundError if a README for the specified subpath does not exist. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of th...
readme_for
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def filename_for(self, subpath): """ Returns the relative filename for the specified subpath, or the root filename if subpath is None. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of the root directory. """ try: filename = ...
Returns the relative filename for the specified subpath, or the root filename if subpath is None. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of the root directory.
filename_for
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def is_binary(self, subpath=None): """ Gets whether the specified subpath is a supported binary file. """ mimetype = self.mimetype_for(subpath) return mimetype and not mimetype.startswith('text/')
Gets whether the specified subpath is a supported binary file.
is_binary
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def last_updated(self, subpath=None): """ Returns the time of the last modification of the Readme or specified subpath, or None if the file does not exist. The return value is a number giving the number of seconds since the epoch (see the time module). Raises werkzeug.e...
Returns the time of the last modification of the Readme or specified subpath, or None if the file does not exist. The return value is a number giving the number of seconds since the epoch (see the time module). Raises werkzeug.exceptions.NotFound if the resulting path ...
last_updated
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def read(self, subpath=None): """ Returns the UTF-8 content of the specified subpath. subpath is expected to already have been normalized. Raises ReadmeNotFoundError if a README for the specified subpath does not exist. Raises werkzeug.exceptions.NotFound if the result...
Returns the UTF-8 content of the specified subpath. subpath is expected to already have been normalized. Raises ReadmeNotFoundError if a README for the specified subpath does not exist. Raises werkzeug.exceptions.NotFound if the resulting path would fall out of the ro...
read
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def filename_for(self, subpath): """ Returns the display filename, or None if subpath is specified since subpaths are not supported for text readers. """ if subpath is not None: return None return self.display_filename
Returns the display filename, or None if subpath is specified since subpaths are not supported for text readers.
filename_for
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def read(self, subpath=None): """ Returns the UTF-8 Readme content. Raises ReadmeNotFoundError if subpath is specified since subpaths are not supported for text readers. """ if subpath is not None: raise ReadmeNotFoundError(subpath) return self.text
Returns the UTF-8 Readme content. Raises ReadmeNotFoundError if subpath is specified since subpaths are not supported for text readers.
read
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def read(self, subpath=None): """ Returns the UTF-8 Readme content. Raises ReadmeNotFoundError if subpath is specified since subpaths are not supported for text readers. """ # Lazily read STDIN if self.text is None and subpath is None: self.text = sel...
Returns the UTF-8 Readme content. Raises ReadmeNotFoundError if subpath is specified since subpaths are not supported for text readers.
read
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def read_stdin(self): """ Reads STDIN until the end of input and returns a unicode string. """ text = sys.stdin.read() # Decode the bytes returned from earlier Python STDIN implementations if sys.version_info[0] < 3 and text is not None: text = text.decode(sy...
Reads STDIN until the end of input and returns a unicode string.
read_stdin
python
joeyespo/grip
grip/readers.py
https://github.com/joeyespo/grip/blob/master/grip/readers.py
MIT
def render(self, text, auth=None): """ Renders the specified markdown content and embedded styles. Raises TypeError if text is not a Unicode string. Raises requests.HTTPError if the request fails. """ # Ensure text is Unicode expected = str if sys.version_info[0]...
Renders the specified markdown content and embedded styles. Raises TypeError if text is not a Unicode string. Raises requests.HTTPError if the request fails.
render
python
joeyespo/grip
grip/renderers.py
https://github.com/joeyespo/grip/blob/master/grip/renderers.py
MIT
def render(self, text, auth=None): """ Renders the specified markdown content and embedded styles. """ if markdown is None: import markdown if UrlizeExtension is None: from .mdx_urlize import UrlizeExtension return markdown.markdown(text, extension...
Renders the specified markdown content and embedded styles.
render
python
joeyespo/grip
grip/renderers.py
https://github.com/joeyespo/grip/blob/master/grip/renderers.py
MIT
def safe_join(directory, *pathnames): """Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory. :param directory: The trusted base directory. :param pathnames: The untrusted path components relative to the base directory....
Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory. :param directory: The trusted base directory. :param pathnames: The untrusted path components relative to the base directory. :return: A safe path.
safe_join
python
joeyespo/grip
grip/_compat.py
https://github.com/joeyespo/grip/blob/master/grip/_compat.py
MIT
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slo...
Class decorator for creating a class with a metaclass.
add_metaclass
python
joeyespo/grip
grip/vendor/six.py
https://github.com/joeyespo/grip/blob/master/grip/vendor/six.py
MIT
def test_exceptions(): """ Test that ReadmeNotFoundError behaves like FileNotFoundError on Python 3 and IOError on Python 2. """ assert str(ReadmeNotFoundError()) == 'README not found' assert (str(ReadmeNotFoundError('.')) == 'No README found at .') assert str(ReadmeNotFoundError('some/path'...
Test that ReadmeNotFoundError behaves like FileNotFoundError on Python 3 and IOError on Python 2.
test_exceptions
python
joeyespo/grip
tests/test_api.py
https://github.com/joeyespo/grip/blob/master/tests/test_api.py
MIT
def disable_torch_init(): """ Disable the redundant torch default initialization to accelerate model creation. """ import torch setattr(torch.nn.Linear, "reset_parameters", lambda self: None) setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
Disable the redundant torch default initialization to accelerate model creation.
disable_torch_init
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/utils.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/utils.py
Apache-2.0
def violates_moderation(text): """ Check whether the text violates OpenAI moderation API. """ url = "https://api.openai.com/v1/moderations" headers = {"Content-Type": "application/json", "Authorization": "Bearer " + os.environ["OPENAI_API_KEY"]} text = text.replace("\n", "") d...
Check whether the text violates OpenAI moderation API.
violates_moderation
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/utils.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/utils.py
Apache-2.0
def split_list(lst, n): """Split a list into n (roughly) equal-sized chunks""" chunk_size = math.ceil(len(lst) / n) # integer division return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
Split a list into n (roughly) equal-sized chunks
split_list
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/eval/model_coco_vqa.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/eval/model_coco_vqa.py
Apache-2.0
def split_list(lst, n): """Split a list into n (roughly) equal-sized chunks""" chunk_size = math.ceil(len(lst) / n) # integer division return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
Split a list into n (roughly) equal-sized chunks
split_list
python
PKU-YuanGroup/Chat-UniVi
ChatUniVi/eval/model_video_consistency.py
https://github.com/PKU-YuanGroup/Chat-UniVi/blob/master/ChatUniVi/eval/model_video_consistency.py
Apache-2.0