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 |
|---|---|---|---|---|---|---|---|
def usage(self):
"Returns the usage message. Make sure it is newline terminated"
msg="""
Usage: program [OPTIONS] FILENAME [SQL|CMD] [SQL|CMD]...
FILENAME is the name of a SQLite database. A new database is
created if the file does not exist.
OPTIONS include:
-init filename read/process named... | Returns the usage message. Make sure it is newline terminated | usage | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def _fmt_c_string(self, v):
"Format as a C string including surrounding double quotes"
if isinstance(v, self._basestring):
op=['"']
for c in v:
if c=="\\":
op.append("\\\\")
elif c=="\r":
op.append("\\r")
... | Format as a C string including surrounding double quotes | _fmt_c_string | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def _fmt_sql_identifier(self, v):
"Return the identifier quoted in SQL syntax if needed (eg table and column names)"
if not len(v): # yes sqlite does allow zero length identifiers
return '""'
nonalnum=re.sub("[A-Za-z_0-9]+", "", v)
if len(nonalnum)==0:
if v.upper(... | Return the identifier quoted in SQL syntax if needed (eg table and column names) | _fmt_sql_identifier | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def output_column(self, header, line):
"""
Items left aligned in space padded columns. They are
truncated if they do not fit. If the width hasn't been
specified for a column then 10 is used unless the column name
(header) is longer in which case that width is used. Use the
... |
Items left aligned in space padded columns. They are
truncated if they do not fit. If the width hasn't been
specified for a column then 10 is used unless the column name
(header) is longer in which case that width is used. Use the
.width command to change column sizes.
... | output_column | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def output_csv(self, header, line):
"""
Items in csv format (comma separated). Use tabs mode for tab
separated. You can use the .separator command to use a
different one after switching mode. A separator of comma uses
double quotes for quoting while other separators do not do ... |
Items in csv format (comma separated). Use tabs mode for tab
separated. You can use the .separator command to use a
different one after switching mode. A separator of comma uses
double quotes for quoting while other separators do not do any
quoting. The Python csv library us... | output_csv | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def output_insert(self, header, line):
"""
Lines as SQL insert statements. The table name is "table"
unless you specified a different one as the second parameter
to the .mode command.
"""
if header:
return
fmt=lambda x: self.colour.colour_value(x, aps... |
Lines as SQL insert statements. The table name is "table"
unless you specified a different one as the second parameter
to the .mode command.
| output_insert | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def output_json(self, header, line):
"""
Each line as a JSON object with a trailing comma. Blobs are
output as base64 encoded strings. You should be using UTF8
output encoding.
"""
if header:
self._output_json_cols=line
return
fmt=lambda ... |
Each line as a JSON object with a trailing comma. Blobs are
output as base64 encoded strings. You should be using UTF8
output encoding.
| output_json | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def output_line(self, header, line):
"""
One value per line in the form 'column = value' with a blank
line between rows.
"""
if header:
w=5
for l in line:
if len(l)>w:
w=len(l)
self._line_info=(w, line)
... |
One value per line in the form 'column = value' with a blank
line between rows.
| output_line | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def output_list(self, header, line):
"All items on one line with separator"
if header:
if not self.header:
return
c=self.colour
fmt=lambda x: c.header+x+c.header_
else:
fmt=lambda x: self.colour.colour_value(x, self._fmt_text_col(x)... | All items on one line with separator | output_list | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def output_python(self, header, line):
"Tuples in Python source form for each row"
if header:
if not self.header:
return
c=self.colour
fmt=lambda x: c.header+self._fmt_python(x)+c.header_
else:
fmt=lambda x: self.colour.colour_value... | Tuples in Python source form for each row | output_python | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def output_tcl(self, header, line):
"Outputs TCL/C style strings using current separator"
# In theory you could paste the output into your source ...
if header:
if not self.header:
return
c=self.colour
fmt=lambda x: c.header+self._fmt_c_string(... | Outputs TCL/C style strings using current separator | output_tcl | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def cmdloop(self, intro=None):
"""Runs the main interactive command loop.
:param intro: Initial text banner to display instead of the
default. Make sure you newline terminate it.
"""
if intro is None:
intro="""
SQLite version %s (APSW %s)
Enter ".help" for instru... | Runs the main interactive command loop.
:param intro: Initial text banner to display instead of the
default. Make sure you newline terminate it.
| cmdloop | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def handle_exception(self):
"""Handles the current exception, printing a message to stderr as appropriate.
It will reraise the exception if necessary (eg if bail is true)"""
eclass,eval,etb=sys.exc_info() # py2&3 compatible way of doing this
if isinstance(eval, SystemExit):
e... | Handles the current exception, printing a message to stderr as appropriate.
It will reraise the exception if necessary (eg if bail is true) | handle_exception | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def process_sql(self, sql, bindings=None, internal=False, summary=None):
"""Processes SQL text consisting of one or more statements
:param sql: SQL to execute
:param bindings: bindings for the *sql*
:param internal: If True then this is an internal execution
(eg the .tables ... | Processes SQL text consisting of one or more statements
:param sql: SQL to execute
:param bindings: bindings for the *sql*
:param internal: If True then this is an internal execution
(eg the .tables or .database command). When executing
internal sql timings are not shown ... | process_sql | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def process_command(self, cmd):
"""Processes a dot command. It is split into parts using the
`shlex.split
<http://docs.python.org/library/shlex.html#shlex.split>`__
function which is roughly the same method used by Unix/POSIX
shells.
"""
if self.echo:
... | Processes a dot command. It is split into parts using the
`shlex.split
<http://docs.python.org/library/shlex.html#shlex.split>`__
function which is roughly the same method used by Unix/POSIX
shells.
| process_command | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_backup(self, cmd):
"""backup ?DB? FILE: Backup DB (default "main") to FILE
Copies the contents of the current database to FILE
overwriting whatever was in FILE. If you have attached databases
then you can specify their name instead of the default of "main".
The bac... | backup ?DB? FILE: Backup DB (default "main") to FILE
Copies the contents of the current database to FILE
overwriting whatever was in FILE. If you have attached databases
then you can specify their name instead of the default of "main".
The backup is done at the page level - SQLite cop... | command_backup | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_colour(self, cmd=[]):
"""colour SCHEME: Selects a colour scheme
Residents of both countries that have not adopted the metric
system may also spell this command without a 'u'. If using a
colour terminal in interactive mode then output is
automatically coloured to mak... | colour SCHEME: Selects a colour scheme
Residents of both countries that have not adopted the metric
system may also spell this command without a 'u'. If using a
colour terminal in interactive mode then output is
automatically coloured to make it more readable. Use 'off' to
tur... | command_colour | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_databases(self, cmd):
"""databases: Lists names and files of attached databases
"""
if len(cmd):
raise self.Error("databases command doesn't take any parameters")
self.push_output()
self.header=True
self.output=self.output_column
self.trun... | databases: Lists names and files of attached databases
| command_databases | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_dump(self, cmd):
"""dump ?TABLE? [TABLE...]: Dumps all or specified tables in SQL text format
The table name is treated as like pattern so you can use % as
a wildcard. You can use dump to make a text based backup of
the database. It is also useful for comparing differences... | dump ?TABLE? [TABLE...]: Dumps all or specified tables in SQL text format
The table name is treated as like pattern so you can use % as
a wildcard. You can use dump to make a text based backup of
the database. It is also useful for comparing differences or
making the data available to... | command_dump | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def set_encoding(self, enc):
"""Saves *enc* as the default encoding, after verifying that
it is valid. You can also include :error to specify error
handling - eg 'cp437:replace'
Raises an exception on invalid encoding or error
"""
enc=enc.split(":", 1)
if len(en... | Saves *enc* as the default encoding, after verifying that
it is valid. You can also include :error to specify error
handling - eg 'cp437:replace'
Raises an exception on invalid encoding or error
| set_encoding | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_encoding(self, cmd):
"""encoding ENCODING: Set the encoding used for new files opened via .output and imports
SQLite and APSW work internally using Unicode and characters.
Files however are a sequence of bytes. An encoding describes
how to convert between bytes and characte... | encoding ENCODING: Set the encoding used for new files opened via .output and imports
SQLite and APSW work internally using Unicode and characters.
Files however are a sequence of bytes. An encoding describes
how to convert between bytes and characters. The default
encoding is utf8 an... | command_encoding | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_explain(self, cmd):
"""explain ON|OFF: Set output mode suitable for explain (default OFF)
Explain shows the underlying SQLite virtual machine code for a
statement. You need to prefix the SQL with explain. For example:
explain select * from table;
This output m... | explain ON|OFF: Set output mode suitable for explain (default OFF)
Explain shows the underlying SQLite virtual machine code for a
statement. You need to prefix the SQL with explain. For example:
explain select * from table;
This output mode formats the explain output nicely. If ... | command_explain | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_help(self, cmd):
"""help ?COMMAND?: Shows list of commands and their usage. If COMMAND is specified then shows detail about that COMMAND. ('.help all' will show detailed help about all commands.)
"""
if not self._help_info:
# buildup help database
self._help... | help ?COMMAND?: Shows list of commands and their usage. If COMMAND is specified then shows detail about that COMMAND. ('.help all' will show detailed help about all commands.)
| command_help | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_import(self, cmd):
"""import FILE TABLE: Imports separated data from FILE into TABLE
Reads data from the file into the named table using the
current separator and encoding. For example if the separator
is currently a comma then the file should be CSV (comma
separate... | import FILE TABLE: Imports separated data from FILE into TABLE
Reads data from the file into the named table using the
current separator and encoding. For example if the separator
is currently a comma then the file should be CSV (comma
separated values).
All values read in are... | command_import | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_autoimport(self, cmd):
"""autoimport FILENAME ?TABLE?: Imports filename creating a table and automatically working out separators and data types (alternative to .import command)
The import command requires that you precisely pre-setup the
table and schema, and set the data separator... | autoimport FILENAME ?TABLE?: Imports filename creating a table and automatically working out separators and data types (alternative to .import command)
The import command requires that you precisely pre-setup the
table and schema, and set the data separators (eg commas or
tabs). In many cases ... | command_autoimport | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_indices(self, cmd):
"""indices TABLE: Lists all indices on table TABLE
"""
if len(cmd)!=1:
raise self.Error("indices takes one table name")
self.push_output()
self.header=False
self.output=self.output_list
try:
self.process_sql... | indices TABLE: Lists all indices on table TABLE
| command_indices | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_load(self, cmd):
"""load FILE ?ENTRY?: Loads a SQLite extension library
Note: Extension loading may not be enabled in the SQLite
library version you are using.
Extensions are an easy way to add new functions and
functionality. For a useful extension look at the bot... | load FILE ?ENTRY?: Loads a SQLite extension library
Note: Extension loading may not be enabled in the SQLite
library version you are using.
Extensions are an easy way to add new functions and
functionality. For a useful extension look at the bottom of
https://sqlite.org/contri... | command_load | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_mode(self, cmd):
"""mode MODE ?TABLE?: Sets output mode to one of"""
if len(cmd) in (1,2):
w=cmd[0]
if w=="tabs":
w="list"
m=getattr(self, "output_"+w, None)
if w!="insert":
if len(cmd)==2:
ra... | mode MODE ?TABLE?: Sets output mode to one of | command_mode | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_nullvalue(self, cmd):
"""nullvalue STRING: Print STRING in place of null values
This affects textual output modes like column and list and
sets how SQL null values are shown. The default is a zero
length string. Insert mode and dumps are not affected by this
settin... | nullvalue STRING: Print STRING in place of null values
This affects textual output modes like column and list and
sets how SQL null values are shown. The default is a zero
length string. Insert mode and dumps are not affected by this
setting. You can use double quotes to supply a zer... | command_nullvalue | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_output(self, cmd):
"""output FILENAME: Send output to FILENAME (or stdout)
If the FILENAME is stdout then output is sent to standard
output from when the shell was started. The file is opened
using the current encoding (change with .encoding command).
"""
# ... | output FILENAME: Send output to FILENAME (or stdout)
If the FILENAME is stdout then output is sent to standard
output from when the shell was started. The file is opened
using the current encoding (change with .encoding command).
| command_output | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_prompt(self, cmd):
"""prompt MAIN ?CONTINUE?: Changes the prompts for first line and continuation lines
The default is to print 'sqlite> ' for the main prompt where
you can enter a dot command or a SQL statement. If the SQL
statement is complete (eg not ; terminated) then y... | prompt MAIN ?CONTINUE?: Changes the prompts for first line and continuation lines
The default is to print 'sqlite> ' for the main prompt where
you can enter a dot command or a SQL statement. If the SQL
statement is complete (eg not ; terminated) then you are
prompted for more using the... | command_prompt | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_read(self, cmd):
"""read FILENAME: Processes SQL and commands in FILENAME (or Python if FILENAME ends with .py)
Treats the specified file as input (a mixture or SQL and/or
dot commands). If the filename ends in .py then it is treated
as Python code instead.
For Pyt... | read FILENAME: Processes SQL and commands in FILENAME (or Python if FILENAME ends with .py)
Treats the specified file as input (a mixture or SQL and/or
dot commands). If the filename ends in .py then it is treated
as Python code instead.
For Python code the symbol 'shell' refers to th... | command_read | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_restore(self, cmd):
"""restore ?DB? FILE: Restore database from FILE into DB (default "main")
Copies the contents of FILE to the current database (default "main").
The backup is done at the page level - SQLite copies the pages as
is. There is no round trip through SQL code.... | restore ?DB? FILE: Restore database from FILE into DB (default "main")
Copies the contents of FILE to the current database (default "main").
The backup is done at the page level - SQLite copies the pages as
is. There is no round trip through SQL code.
| command_restore | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_schema(self, cmd):
"""schema ?TABLE? [TABLE...]: Shows SQL for table
If you give one or more tables then their schema is listed
(including indices). If you don't specify any then all
schemas are listed. TABLE is a like pattern so you can % for
wildcards.
"""... | schema ?TABLE? [TABLE...]: Shows SQL for table
If you give one or more tables then their schema is listed
(including indices). If you don't specify any then all
schemas are listed. TABLE is a like pattern so you can % for
wildcards.
| command_schema | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_separator(self, cmd):
"""separator STRING: Change separator for output mode and .import
You can use quotes and backslashes. For example to set the
separator to space tab space you can use:
.separator " \\t "
The setting is automatically changed when you switch t... | separator STRING: Change separator for output mode and .import
You can use quotes and backslashes. For example to set the
separator to space tab space you can use:
.separator " \t "
The setting is automatically changed when you switch to csv or
tabs output mode. You should... | command_separator | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_show(self, cmd):
"""show: Show the current values for various settings."""
if len(cmd)>1:
raise self.Error("show takes at most one parameter")
if len(cmd):
what=cmd[0]
if what not in self._shows:
raise self.Error("Unknown show: '%s'... | show: Show the current values for various settings. | command_show | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_tables(self, cmd):
"""tables ?PATTERN?: Lists names of tables matching LIKE pattern
This also returns views.
"""
self.push_output()
self.output=self.output_list
self.header=False
try:
if len(cmd)==0:
cmd=['%']
... | tables ?PATTERN?: Lists names of tables matching LIKE pattern
This also returns views.
| command_tables | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_timeout(self, cmd):
"""timeout MS: Try opening locked tables for MS milliseconds
If a database is locked by another process SQLite will keep
retrying. This sets how many thousandths of a second it will
keep trying for. If you supply zero or a negative number then
a... | timeout MS: Try opening locked tables for MS milliseconds
If a database is locked by another process SQLite will keep
retrying. This sets how many thousandths of a second it will
keep trying for. If you supply zero or a negative number then
all busy handlers are disabled.
| command_timeout | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_timer(self, cmd):
"""timer ON|OFF: Control printing of time and resource usage after each query
The values displayed are in seconds when shown as floating
point or an absolute count. Only items that have changed
since starting the query are shown. On non-Windows platforms
... | timer ON|OFF: Control printing of time and resource usage after each query
The values displayed are in seconds when shown as floating
point or an absolute count. Only items that have changed
since starting the query are shown. On non-Windows platforms
considerably more information can... | command_timer | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def command_width(self, cmd):
"""width NUM NUM ...: Set the column widths for "column" mode
In "column" output mode, each column is a fixed width with values truncated to
fit. Specify new widths using this command. Use a negative number
to right justify and zero for default column wid... | width NUM NUM ...: Set the column widths for "column" mode
In "column" output mode, each column is a fixed width with values truncated to
fit. Specify new widths using this command. Use a negative number
to right justify and zero for default column width.
| command_width | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def _terminal_width(self):
"""Works out the terminal width which is used for word wrapping
some output (eg .help)"""
try:
if sys.platform=="win32":
import ctypes, struct
h=ctypes.windll.kernel32.GetStdHandle(-12) # -12 is stderr
buf=cty... | Works out the terminal width which is used for word wrapping
some output (eg .help) | _terminal_width | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def push_output(self):
"""Saves the current output settings onto a stack. See
:meth:`pop_output` for more details as to why you would use
this."""
o={}
for k in "separator", "header", "nullvalue", "output", "widths", "truncate":
o[k]=getattr(self, k)
self._ou... | Saves the current output settings onto a stack. See
:meth:`pop_output` for more details as to why you would use
this. | push_output | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def pop_output(self):
"""Restores most recently pushed output. There are many
output parameters such as nullvalue, mode
(list/tcl/html/insert etc), column widths, header etc. If you
temporarily need to change some settings then
:meth:`push_output`, change the settings and then ... | Restores most recently pushed output. There are many
output parameters such as nullvalue, mode
(list/tcl/html/insert etc), column widths, header etc. If you
temporarily need to change some settings then
:meth:`push_output`, change the settings and then pop the old
ones back.
... | pop_output | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def _append_input_description(self):
"""When displaying an error in :meth:`handle_exception` we
want to give context such as when the commands being executed
came from a .read command (which in turn could execute another
.read).
"""
if self.interactive:
return... | When displaying an error in :meth:`handle_exception` we
want to give context such as when the commands being executed
came from a .read command (which in turn could execute another
.read).
| _append_input_description | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def fixup_backslashes(self, s):
"""Implements the various backlash sequences in s such as
turning backslash t into a tab.
This function is needed because shlex does not do it for us.
"""
if "\\" not in s: return s
# See the resolve_backslashes function in SQLite shell so... | Implements the various backlash sequences in s such as
turning backslash t into a tab.
This function is needed because shlex does not do it for us.
| fixup_backslashes | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def write(self, dest, text):
"""Writes text to dest. dest will typically be one of self.stdout or self.stderr."""
# ensure text is unicode to catch codeset issues here
if type(text)!=unicode:
text=unicode(text)
try:
dest.write(text)
... | Writes text to dest. dest will typically be one of self.stdout or self.stderr. | write | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def getline(self, prompt=""):
"""Returns a single line of input (may be incomplete SQL) from self.stdin.
If EOF is reached then return None. Do not include trailing
newline in return.
"""
self.stdout.flush()
self.stderr.flush()
try:
if self.interacti... | Returns a single line of input (may be incomplete SQL) from self.stdin.
If EOF is reached then return None. Do not include trailing
newline in return.
| getline | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def getcompleteline(self):
"""Returns a complete input.
For dot commands it will be one line. For SQL statements it
will be as many as is necessary to have a
:meth:`~apsw.complete` statement (ie semicolon terminated).
Returns None on end of file."""
try:
sel... | Returns a complete input.
For dot commands it will be one line. For SQL statements it
will be as many as is necessary to have a
:meth:`~apsw.complete` statement (ie semicolon terminated).
Returns None on end of file. | getcompleteline | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def handle_interrupt(self):
"""Deal with keyboard interrupt (typically Control-C). It
will :meth:`~Connection.interrupt` the database and print"^C" if interactive."""
self.db.interrupt()
if not self.bail and self.interactive:
self.write(self.stderr, "^C\n")
retur... | Deal with keyboard interrupt (typically Control-C). It
will :meth:`~Connection.interrupt` the database and print"^C" if interactive. | handle_interrupt | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def process_complete_line(self, command):
"""Given some text will call the appropriate method to process
it (eg :meth:`process_sql` or :meth:`process_command`)"""
try:
if len(command.strip())==0:
return
if command[0]==".":
self.process_comm... | Given some text will call the appropriate method to process
it (eg :meth:`process_sql` or :meth:`process_command`) | process_complete_line | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def push_input(self):
"""Saves the current input parameters to a stack. See :meth:`pop_input`."""
d={}
for i in "interactive", "stdin", "input_line_number":
d[i]=getattr(self, i)
self._input_stack.append(d) | Saves the current input parameters to a stack. See :meth:`pop_input`. | push_input | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def pop_input(self):
"""Restore most recently pushed input parameters (interactive,
self.stdin, linenumber etc). Use this if implementing a
command like read. Push the current input, read the file and
then pop the input to go back to before.
"""
assert(len(self._input_s... | Restore most recently pushed input parameters (interactive,
self.stdin, linenumber etc). Use this if implementing a
command like read. Push the current input, read the file and
then pop the input to go back to before.
| pop_input | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def complete(self, token, state):
"""Return a possible completion for readline
This function is called with state starting at zero to get the
first completion, then one/two/three etc until you return None. The best
implementation is to generate the list when state==0, save it,
... | Return a possible completion for readline
This function is called with state starting at zero to get the
first completion, then one/two/three etc until you return None. The best
implementation is to generate the list when state==0, save it,
and provide members on each increase.
... | complete | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def _get_prev_tokens(self, line, end):
"Returns the tokens prior to pos end in the line"
return re.findall(r'"?\w+"?', line[:end]) | Returns the tokens prior to pos end in the line | _get_prev_tokens | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def complete_sql(self, line, token, beg, end):
"""Provide some completions for SQL
:param line: The current complete input line
:param token: The word readline is looking for matches
:param beg: Integer offset of token in line
:param end: Integer end of token in line
:re... | Provide some completions for SQL
:param line: The current complete input line
:param token: The word readline is looking for matches
:param beg: Integer offset of token in line
:param end: Integer end of token in line
:return: A list of completions, or an empty list if none
... | complete_sql | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def complete_command(self, line, token, beg, end):
"""Provide some completions for dot commands
:param line: The current complete input line
:param token: The word readline is looking for matches
:param beg: Integer offset of token in line
:param end: Integer end of token in lin... | Provide some completions for dot commands
:param line: The current complete input line
:param token: The word readline is looking for matches
:param beg: Integer offset of token in line
:param end: Integer end of token in line
:return: A list of completions, or an empty list if ... | complete_command | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def get_resource_usage(self):
"""Return a dict of various numbers (ints or floats). The
.timer command shows the difference between before and after
results of what this returns by calling :meth:`display_timing`"""
if sys.platform=="win32":
import ctypes, time, platform
... | Return a dict of various numbers (ints or floats). The
.timer command shows the difference between before and after
results of what this returns by calling :meth:`display_timing` | get_resource_usage | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def display_timing(self, b4, after):
"""Writes the difference between b4 and after to self.stderr.
The data is dictionaries returned from
:meth:`get_resource_usage`."""
v=list(b4.keys())
for i in after:
if i not in v:
v.append(i)
v.sort()
... | Writes the difference between b4 and after to self.stderr.
The data is dictionaries returned from
:meth:`get_resource_usage`. | display_timing | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def main():
# Docstring must start on second line so dedenting works correctly
"""
Call this to run the interactive shell. It automatically passes
in sys.argv[1:] and exits Python when done.
"""
try:
s=Shell()
_,_,cmds=s.process_args(sys.argv[1:])
if len(cmds)==0:
... |
Call this to run the interactive shell. It automatically passes
in sys.argv[1:] and exits Python when done.
| main | python | plasticityai/magnitude | pymagnitude/third_party/_apsw/tools/shell.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_apsw/tools/shell.py | MIT |
def system_with_status_and_output(
command, attach_env=True, should_silence_err=False,
exit_with_error_message=None, _stdout=PIPE):
"""Runs a system command with various options and returns
the status of the command and the output of the command.
"""
if should_silence_err:
stderr... | Runs a system command with various options and returns
the status of the command and the output of the command.
| system_with_status_and_output | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/setup.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/setup.py | MIT |
def system_with_output(
command, attach_env=True, should_silence_err=False,
exit_with_error_message=None):
"""Runs a system command with various options and returns
the output of the command.
"""
return system_with_status_and_output(
command, attach_env, should_silence_err, exit_... | Runs a system command with various options and returns
the output of the command.
| system_with_output | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/setup.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/setup.py | MIT |
def _sqlite_try_max_variable_number(num):
""" Tests whether SQLite can handle num variables """
db = sqlite3.connect(':memory:')
try:
db.cursor().execute(
"SELECT 1 IN (" + ",".join(["?"] * num) + ")",
([0] * num)
).fetchall()
return num
except BaseExcepti... | Tests whether SQLite can handle num variables | _sqlite_try_max_variable_number | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def __new__(cls, *args, **kwargs):
""" Returns a concatenated magnitude object, if Magnitude parameters """
if len(args) > 0 and isinstance(args[0], Magnitude):
obj = object.__new__(ConcatenatedMagnitude, *args, **kwargs)
obj.__init__(*args, **kwargs)
else:
ob... | Returns a concatenated magnitude object, if Magnitude parameters | __new__ | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _db(self, force_new=False):
"""Returns a cursor to the database. Each thread gets its
own cursor.
"""
identifier = threading.current_thread().ident
conn_exists = identifier in self._cursors
if not conn_exists or force_new:
if self.fd:
if os... | Returns a cursor to the database. Each thread gets its
own cursor.
| _db | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _key_t(self, key):
"""Transforms a key to lower case depending on case
sensitivity.
"""
if self.case_insensitive and (isinstance(key, str) or
isinstance(key, unicode)):
return key.lower()
return key | Transforms a key to lower case depending on case
sensitivity.
| _key_t | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _oov_key_t(self, key):
"""Transforms a key for out-of-vocabulary lookup.
"""
is_str = isinstance(key, str) or isinstance(key, unicode)
if is_str:
key = Magnitude.BOW + self._key_t(key) + Magnitude.EOW
return is_str, self._key_shrunk_2(key)
return is_st... | Transforms a key for out-of-vocabulary lookup.
| _oov_key_t | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _oov_english_stem_english_ixes(self, key):
"""Strips away common English prefixes and suffixes."""
key_lower = key.lower()
start_idx = 0
end_idx = 0
for p in Magnitude.ENGLISH_PREFIXES:
if key_lower[:len(p)] == p:
start_idx = len(p)
... | Strips away common English prefixes and suffixes. | _oov_english_stem_english_ixes | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _oov_stem(self, key):
"""Strips away common prefixes and suffixes."""
if self.language == 'en':
return self._oov_english_stem_english_ixes(key)
return key | Strips away common prefixes and suffixes. | _oov_stem | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _db_query_similar_keys_vector(self, key, orig_key, topn=3):
"""Finds similar keys in the database and gets the mean vector."""
def _sql_escape_single(s):
return s.replace("'", "''")
def _sql_escape_fts(s):
return ''.join("\\" + c if c in Magnitude.FTS_SPECIAL
... | Finds similar keys in the database and gets the mean vector. | _db_query_similar_keys_vector | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _seed(self, val):
"""Returns a unique seed for val and the (optional) namespace."""
if self._namespace:
return xxhash.xxh32(self._namespace + Magnitude.RARE_CHAR +
val.encode('utf-8')).intdigest()
else:
return xxhash.xxh32(val.encode('u... | Returns a unique seed for val and the (optional) namespace. | _seed | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _out_of_vocab_vector(self, key):
"""Generates a random vector based on the hash of the key."""
orig_key = key
is_str, key = self._oov_key_t(key)
if not is_str:
seed = self._seed(type(key).__name__)
Magnitude.OOV_RNG_LOCK.acquire()
np.random.seed(se... | Generates a random vector based on the hash of the key. | _out_of_vocab_vector | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _db_batch_generator(self, params):
""" Generates batches of paramaters that respect
SQLite's MAX_VARIABLE_NUMBER """
if len(params) <= Magnitude.SQLITE_MAX_VARIABLE_NUMBER:
yield params
else:
it = iter(params)
for batch in \
ite... | Generates batches of paramaters that respect
SQLite's MAX_VARIABLE_NUMBER | _db_batch_generator | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _db_full_result_to_vec(self, result, put_cache=True):
"""Converts a full database result to a vector."""
result_key = result[0]
if self._query_is_cached(result_key):
return (result_key, self.query(result_key))
else:
vec = self._db_result_to_vec(result[1:])
... | Converts a full database result to a vector. | _db_full_result_to_vec | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _vector_for_key(self, key):
"""Queries the database for a single key."""
result = self._db().execute(
"""
SELECT *
FROM `magnitude`
WHERE key = ?
ORDER BY key = ? COLLATE BINARY DESC
LIMIT 1;""",
... | Queries the database for a single key. | _vector_for_key | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _vectors_for_keys(self, keys):
"""Queries the database for multiple keys."""
unseen_keys = tuple(key for key in keys
if not self._query_is_cached(key))
unseen_keys_map = {}
if len(unseen_keys) > 0:
unseen_keys_map = {self._key_t(k): i for i, k ... | Queries the database for multiple keys. | _vectors_for_keys | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _key_for_index(self, index, return_vector=True):
"""Queries the database the key at a single index."""
columns = "key"
if return_vector:
columns = "*"
result = self._db().execute(
"""
SELECT """ + columns + """
FROM `magnitude`
... | Queries the database the key at a single index. | _key_for_index | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _keys_for_indices(self, indices, return_vector=True):
"""Queries the database for the keys of multiple indices."""
unseen_indices = tuple(int(index + 1) for index in indices
if self._key_for_index_cached._cache.get(((index,), # noqa
... | Queries the database for the keys of multiple indices. | _keys_for_indices | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def query(self, q, pad_to_length=None,
pad_left=None, truncate_left=None):
"""Handles a query of keys which could be a single key, a
1-D list of keys, or a 2-D list of keys.
"""
pad_to_length = pad_to_length or self.pad_to_length
pad_left = pad_left or self.pad_left... | Handles a query of keys which could be a single key, a
1-D list of keys, or a 2-D list of keys.
| query | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def index(self, q, return_vector=True):
"""Gets a key for an index or multiple indices."""
if isinstance(q, list) or isinstance(q, tuple):
return self._keys_for_indices(q, return_vector=return_vector)
else:
return self._key_for_index_cached(q, return_vector=return_vector) | Gets a key for an index or multiple indices. | index | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _query_numpy(self, key):
"""Returns the query for a key, forcibly converting the
resulting vector to a numpy array.
"""
key_is_ndarray = isinstance(key, np.ndarray)
key_is_list = isinstance(key, list)
key_len_ge_0 = key_is_list and len(key) > 0
key_0_is_number... | Returns the query for a key, forcibly converting the
resulting vector to a numpy array.
| _query_numpy | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _query_is_cached(self, key):
"""Checks if the query been cached by Magnitude."""
return ((self._vector_for_key_cached._cache.get((key,)) is not None) or ( # noqa
self._out_of_vocab_vector_cached._cache.get((key,)) is not None)) | Checks if the query been cached by Magnitude. | _query_is_cached | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def distance(self, key, q):
"""Calculates the distance from key to the key(s) in q."""
a = self._query_numpy(key)
if not isinstance(q, list):
b = self._query_numpy(q)
return np.linalg.norm(a - b)
else:
return [np.linalg.norm(a - self._query_numpy(b)) f... | Calculates the distance from key to the key(s) in q. | distance | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def similarity(self, key, q):
"""Calculates the similarity from key to the key(s) in q."""
a = self._query_numpy(key)
if not isinstance(q, list):
b = self._query_numpy(q)
return np.inner(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
else:
bs = [self.... | Calculates the similarity from key to the key(s) in q. | similarity | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def most_similar_to_given(self, key, q):
"""Calculates the most similar key in q to key."""
distances = self.distance(key, q)
min_index, _ = min(enumerate(distances), key=operator.itemgetter(1))
return q[min_index] | Calculates the most similar key in q to key. | most_similar_to_given | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def doesnt_match(self, q):
"""Given a set of keys, figures out which key doesn't
match the rest.
"""
mean_vector = np.mean(self._query_numpy([[sq] for sq in q]), axis=0)
mean_unit_vector = mean_vector / np.linalg.norm(mean_vector)
distances = [np.linalg.norm(mean_unit_vec... | Given a set of keys, figures out which key doesn't
match the rest.
| doesnt_match | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _db_query_similarity(
self,
positive,
negative,
min_similarity=None,
topn=10,
exclude_keys=set(),
return_similarities=False,
method='distance',
effort=1.0):
"""Runs a database query to find vectors cl... | Runs a database query to find vectors close to vector. | _db_query_similarity | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def most_similar(self, positive, negative=[], topn=10, min_similarity=None,
return_similarities=True):
"""Finds the topn most similar vectors under or equal
to max distance.
"""
positive, negative = self._handle_pos_neg_args(positive, negative)
return self._... | Finds the topn most similar vectors under or equal
to max distance.
| most_similar | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def most_similar_cosmul(self, positive, negative=[], topn=10,
min_similarity=None, return_similarities=True):
"""Finds the topn most similar vectors under or equal to max
distance using 3CosMul:
[Levy and Goldberg](http://www.aclweb.org/anthology/W14-1618)
"""... | Finds the topn most similar vectors under or equal to max
distance using 3CosMul:
[Levy and Goldberg](http://www.aclweb.org/anthology/W14-1618)
| most_similar_cosmul | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def most_similar_approx(
self,
positive,
negative=[],
topn=10,
min_similarity=None,
return_similarities=True,
effort=1.0):
"""Approximates the topn most similar vectors under or equal to max
distance using Annoy:
... | Approximates the topn most similar vectors under or equal to max
distance using Annoy:
https://github.com/spotify/annoy
| most_similar_approx | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def closer_than(self, key, q, topn=None):
"""Finds all keys closer to key than q is to key."""
epsilon = (10.0 / 10**6)
min_similarity = self.similarity(key, q) + epsilon
return self.most_similar(key, topn=topn, min_similarity=min_similarity,
return_simi... | Finds all keys closer to key than q is to key. | closer_than | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def get_vectors_mmap(self):
"""Gets a numpy.memmap of all vectors, blocks if it is still
being built.
"""
if self._all_vectors is None:
while True:
if not self.setup_for_mmap:
self._setup_for_mmap()
try:
... | Gets a numpy.memmap of all vectors, blocks if it is still
being built.
| get_vectors_mmap | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def get_approx_index_chunks(self):
"""Gets decompressed chunks of the AnnoyIndex of the vectors from
the database."""
try:
db = self._db(force_new=True)
with lz4.frame.LZ4FrameDecompressor() as decompressor:
chunks = db.execute(
"""
... | Gets decompressed chunks of the AnnoyIndex of the vectors from
the database. | get_approx_index_chunks | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def get_approx_index(self):
"""Gets an AnnoyIndex of the vectors from the database."""
chunks = self.get_approx_index_chunks()
if self._approx_index is None:
while True:
if not self.setup_for_mmap:
self._setup_for_mmap()
try:
... | Gets an AnnoyIndex of the vectors from the database. | get_approx_index | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _iter(self, put_cache):
"""Yields keys and vectors for all vectors in the store."""
try:
db = self._db(force_new=True)
results = db.execute(
"""
SELECT *
FROM `magnitude`
""")
for result in re... | Yields keys and vectors for all vectors in the store. | _iter | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def __getitem__(self, q):
"""Performs the index method when indexed."""
if isinstance(q, slice):
return self.index(list(range(*q.indices(self.length))),
return_vector=True)
else:
return self.index(q, return_vector=True) | Performs the index method when indexed. | __getitem__ | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _take(self, q, multikey, i):
"""Selects only the i'th element from the inner-most axis and
reduces the dimensions of the tensor q by 1.
"""
if multikey == -1:
return q
else:
cut = np.take(q, [i], axis=multikey)
result = np.reshape(cut, np.s... | Selects only the i'th element from the inner-most axis and
reduces the dimensions of the tensor q by 1.
| _take | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _hstack(self, l, use_numpy):
"""Horizontally stacks NumPy arrays or Python lists"""
if use_numpy:
return np.concatenate(l, axis=-1)
else:
return list(chain.from_iterable(l)) | Horizontally stacks NumPy arrays or Python lists | _hstack | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def _dstack(self, l, use_numpy):
"""Depth stacks NumPy arrays or Python lists"""
if use_numpy:
return np.concatenate(l, axis=-1)
else:
return [self._hstack((l3[example] for l3 in l),
use_numpy=use_numpy) for example in xrange(len(l[0]))] ... | Depth stacks NumPy arrays or Python lists | _dstack | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def query(self, q, pad_to_length=None,
pad_left=None, truncate_left=None):
"""Handles a query of keys which could be a single key, a
1-D list of keys, or a 2-D list of keys.
"""
# Check if keys are specified for each concatenated model
multikey = -1
if isin... | Handles a query of keys which could be a single key, a
1-D list of keys, or a 2-D list of keys.
| query | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
def batchify(X, y, batch_size): # noqa: N803
""" Creates an iterator that chunks `X` and `y` into batches
that each contain `batch_size` elements and loops forever"""
X_batch_generator = cycle([X[i: i + batch_size] # noqa: N806
for i in xrange(0, len(X), batc... | Creates an iterator that chunks `X` and `y` into batches
that each contain `batch_size` elements and loops forever | batchify | python | plasticityai/magnitude | pymagnitude/third_party/_pysqlite/__init__.py | https://github.com/plasticityai/magnitude/blob/master/pymagnitude/third_party/_pysqlite/__init__.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.