_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q226700 | Path.add2python | train | def add2python(self, module=None, up=0, down=None, front=False,
must_exist=True):
'''Add a directory to the python path.
:parameter module: Optional module name to try to import once we
have found the directory
:parameter up: number of level to go up the directory... | python | {
"resource": ""
} |
q226701 | HttpBin.get | train | def get(self, request):
'''The home page of this router'''
ul = Html('ul')
for router in sorted(self.routes, key=lambda r: r.creation_count):
a = router.link(escape(router.route.path))
a.addClass(router.name)
for method in METHODS:
if router.ge... | python | {
"resource": ""
} |
q226702 | HttpBin.stats | train | def stats(self, request):
'''Live stats for the server.
Try sending lots of requests
'''
# scheme = 'wss' if request.is_secure else 'ws'
# host = request.get('HTTP_HOST')
# address = '%s://%s/stats' % (scheme, host)
doc = HtmlDocument(title='Live server stats', m... | python | {
"resource": ""
} |
q226703 | get_preparation_data | train | def get_preparation_data(name):
'''
Return info about parent needed by child to unpickle process object.
Monkey-patch from
'''
d = dict(
name=name,
sys_path=sys.path,
sys_argv=sys.argv,
log_to_stderr=_log_to_stderr,
orig_dir=process.ORIGINAL_DIR,
... | python | {
"resource": ""
} |
q226704 | remote_call | train | def remote_call(request, cls, method, args, kw):
'''Command for executing remote calls on a remote object
'''
actor = request.actor
name = 'remote_%s' % cls.__name__
if not hasattr(actor, name):
object = cls(actor)
setattr(actor, name, object)
else:
object = getattr(actor... | python | {
"resource": ""
} |
q226705 | Skiplist.clear | train | def clear(self):
'''Clear the container from all data.'''
self._size = 0
self._level = 1
self._head = Node('HEAD', None,
[None]*SKIPLIST_MAXLEVEL,
[1]*SKIPLIST_MAXLEVEL) | python | {
"resource": ""
} |
q226706 | Skiplist.extend | train | def extend(self, iterable):
'''Extend this skiplist with an iterable over
``score``, ``value`` pairs.
'''
i = self.insert
for score_values in iterable:
i(*score_values) | python | {
"resource": ""
} |
q226707 | Skiplist.remove_range | train | def remove_range(self, start, end, callback=None):
'''Remove a range by rank.
This is equivalent to perform::
del l[start:end]
on a python list.
It returns the number of element removed.
'''
N = len(self)
if start < 0:
start = max(N + st... | python | {
"resource": ""
} |
q226708 | Skiplist.remove_range_by_score | train | def remove_range_by_score(self, minval, maxval, include_min=True,
include_max=True, callback=None):
'''Remove a range with scores between ``minval`` and ``maxval``.
:param minval: the start value of the range to remove
:param maxval: the end value of the range to r... | python | {
"resource": ""
} |
q226709 | Skiplist.count | train | def count(self, minval, maxval, include_min=True, include_max=True):
'''Returns the number of elements in the skiplist with a score
between min and max.
'''
rank1 = self.rank(minval)
if rank1 < 0:
rank1 = -rank1 - 1
elif not include_min:
rank1 += 1... | python | {
"resource": ""
} |
q226710 | Accept.quality | train | def quality(self, key):
"""Returns the quality of the key.
.. versionadded:: 0.6
In previous versions you had to use the item-lookup syntax
(eg: ``obj[key]`` instead of ``obj.quality(key)``)
"""
for item, quality in self:
if self._value_matches(key, ite... | python | {
"resource": ""
} |
q226711 | Accept.to_header | train | def to_header(self):
"""Convert the header set into an HTTP header string."""
result = []
for value, quality in self:
if quality != 1:
value = '%s;q=%s' % (value, quality)
result.append(value)
return ','.join(result) | python | {
"resource": ""
} |
q226712 | Accept.best_match | train | def best_match(self, matches, default=None):
"""Returns the best match from a list of possible matches based
on the quality of the client. If two items have the same quality,
the one is returned that comes first.
:param matches: a list of matches to check for
:param default: th... | python | {
"resource": ""
} |
q226713 | convert_bytes | train | def convert_bytes(b):
'''Convert a number of bytes into a human readable memory usage, bytes,
kilo, mega, giga, tera, peta, exa, zetta, yotta'''
if b is None:
return '#NA'
for s in reversed(memory_symbols):
if b >= memory_size[s]:
value = float(b) / memory_size[s]
ret... | python | {
"resource": ""
} |
q226714 | process_info | train | def process_info(pid=None):
'''Returns a dictionary of system information for the process ``pid``.
It uses the psutil_ module for the purpose. If psutil_ is not available
it returns an empty dictionary.
.. _psutil: http://code.google.com/p/psutil/
'''
if psutil is None: # pragma nocover
... | python | {
"resource": ""
} |
q226715 | TcpServer.start_serving | train | async def start_serving(self, address=None, sockets=None,
backlog=100, sslcontext=None):
"""Start serving.
:param address: optional address to bind to
:param sockets: optional list of sockets to bind to
:param backlog: Number of maximum connections
:p... | python | {
"resource": ""
} |
q226716 | TcpServer._close_connections | train | def _close_connections(self, connection=None, timeout=5):
"""Close ``connection`` if specified, otherwise close all connections.
Return a list of :class:`.Future` called back once the connection/s
are closed.
"""
all = []
if connection:
waiter = connection.ev... | python | {
"resource": ""
} |
q226717 | DatagramServer.start_serving | train | async def start_serving(self, address=None, sockets=None, **kw):
"""create the server endpoint.
"""
if self._server:
raise RuntimeError('Already serving')
server = DGServer(self._loop)
loop = self._loop
if sockets:
for sock in sockets:
... | python | {
"resource": ""
} |
q226718 | SocketServer.monitor_start | train | async def monitor_start(self, monitor):
'''Create the socket listening to the ``bind`` address.
If the platform does not support multiprocessing sockets set the
number of workers to 0.
'''
cfg = self.cfg
if (not platform.has_multiprocessing_socket or
cfg.... | python | {
"resource": ""
} |
q226719 | SocketServer.create_server | train | async def create_server(self, worker, protocol_factory, address=None,
sockets=None, idx=0):
'''Create the Server which will listen for requests.
:return: a :class:`.TcpServer`.
'''
cfg = self.cfg
max_requests = cfg.max_requests
if max_requests... | python | {
"resource": ""
} |
q226720 | RedisPubSub.channels | train | def channels(self, pattern=None):
'''Lists the currently active channels matching ``pattern``
'''
if pattern:
return self.store.execute('PUBSUB', 'CHANNELS', pattern)
else:
return self.store.execute('PUBSUB', 'CHANNELS') | python | {
"resource": ""
} |
q226721 | RedisChannels.lock | train | def lock(self, name, **kwargs):
"""Global distributed lock
"""
return self.pubsub.store.client().lock(self.prefixed(name), **kwargs) | python | {
"resource": ""
} |
q226722 | RedisChannels.publish | train | async def publish(self, channel, event, data=None):
"""Publish a new ``event`` on a ``channel``
:param channel: channel name
:param event: event name
:param data: optional payload to include in the event
:return: a coroutine and therefore it must be awaited
"""
m... | python | {
"resource": ""
} |
q226723 | RedisChannels.close | train | async def close(self):
"""Close channels and underlying pubsub handler
:return: a coroutine and therefore it must be awaited
"""
push_connection = self.pubsub.push_connection
self.status = self.statusType.closed
if push_connection:
push_connection.event('conn... | python | {
"resource": ""
} |
q226724 | RequestBase.origin_req_host | train | def origin_req_host(self):
"""Required by Cookies handlers
"""
if self.history:
return self.history[0].request.origin_req_host
else:
return scheme_host_port(self.url)[1] | python | {
"resource": ""
} |
q226725 | HttpRequest.get_header | train | def get_header(self, header_name, default=None):
"""Retrieve ``header_name`` from this request headers.
"""
return self.headers.get(
header_name, self.unredirected_headers.get(header_name, default)) | python | {
"resource": ""
} |
q226726 | HttpRequest.remove_header | train | def remove_header(self, header_name):
"""Remove ``header_name`` from this request.
"""
val1 = self.headers.pop(header_name, None)
val2 = self.unredirected_headers.pop(header_name, None)
return val1 or val2 | python | {
"resource": ""
} |
q226727 | HttpResponse.raw | train | def raw(self):
"""A raw asynchronous Http response
"""
if self._raw is None:
self._raw = HttpStream(self)
return self._raw | python | {
"resource": ""
} |
q226728 | HttpResponse.links | train | def links(self):
"""Returns the parsed header links of the response, if any
"""
headers = self.headers or {}
header = headers.get('link')
li = {}
if header:
links = parse_header_links(header)
for link in links:
key = link.get('rel')... | python | {
"resource": ""
} |
q226729 | HttpResponse.text | train | def text(self):
"""Decode content as a string.
"""
data = self.content
return data.decode(self.encoding or 'utf-8') if data else '' | python | {
"resource": ""
} |
q226730 | HttpResponse.decode_content | train | def decode_content(self):
"""Return the best possible representation of the response body.
"""
ct = self.headers.get('content-type')
if ct:
ct, options = parse_options_header(ct)
charset = options.get('charset')
if ct in JSON_CONTENT_TYPES:
... | python | {
"resource": ""
} |
q226731 | HttpClient.request | train | def request(self, method, url, **params):
"""Constructs and sends a request to a remote server.
It returns a :class:`.Future` which results in a
:class:`.HttpResponse` object.
:param method: request method for the :class:`HttpRequest`.
:param url: URL for the :class:`HttpReques... | python | {
"resource": ""
} |
q226732 | HttpClient.ssl_context | train | def ssl_context(self, verify=True, cert_reqs=None,
check_hostname=False, certfile=None, keyfile=None,
cafile=None, capath=None, cadata=None, **kw):
"""Create a SSL context object.
This method should not be called by from user code
"""
assert ssl, ... | python | {
"resource": ""
} |
q226733 | HttpClient.create_tunnel_connection | train | async def create_tunnel_connection(self, req):
"""Create a tunnel connection
"""
tunnel_address = req.tunnel_address
connection = await self.create_connection(tunnel_address)
response = connection.current_consumer()
for event in response.events().values():
eve... | python | {
"resource": ""
} |
q226734 | Configurator.python_path | train | def python_path(self, script):
"""Called during initialisation to obtain the ``script`` name.
If ``script`` does not evaluate to ``True`` it is evaluated from
the ``__main__`` import. Returns the real path of the python
script which runs the application.
"""
if not scrip... | python | {
"resource": ""
} |
q226735 | Configurator.start | train | def start(self, exit=True):
"""Invoked the application callable method and start
the ``arbiter`` if it wasn't already started.
It returns a :class:`~asyncio.Future` called back once the
application/applications are running. It returns ``None`` if
called more than once.
"... | python | {
"resource": ""
} |
q226736 | Application.stop | train | def stop(self, actor=None):
"""Stop the application
"""
if actor is None:
actor = get_actor()
if actor and actor.is_arbiter():
monitor = actor.get_actor(self.name)
if monitor:
return monitor.stop()
raise RuntimeError('Cannot sto... | python | {
"resource": ""
} |
q226737 | set_owner_process | train | def set_owner_process(uid, gid):
""" set user and group of workers processes """
if gid:
try:
os.setgid(gid)
except OverflowError:
# versions of python < 2.6.2 don't manage unsigned int for
# groups like on osx or fedora
os.setgid(-ctypes.c_int(-gi... | python | {
"resource": ""
} |
q226738 | wait | train | def wait(value, must_be_child=False):
'''Wait for a possible asynchronous value to complete.
'''
current = getcurrent()
parent = current.parent
if must_be_child and not parent:
raise MustBeInChildGreenlet('Cannot wait on main greenlet')
return parent.switch(value) if parent else value | python | {
"resource": ""
} |
q226739 | run_in_greenlet | train | def run_in_greenlet(callable):
"""Decorator to run a ``callable`` on a new greenlet.
A ``callable`` decorated with this decorator returns a coroutine
"""
@wraps(callable)
async def _(*args, **kwargs):
green = greenlet(callable)
# switch to the new greenlet
result = green.swi... | python | {
"resource": ""
} |
q226740 | build_response | train | def build_response(content, code=200):
"""Build response, add headers"""
response = make_response( jsonify(content), content['code'] )
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Headers'] = \
'Origin, X-Requested-With, Content-Type, Accept, A... | python | {
"resource": ""
} |
q226741 | SqlData.post | train | def post(self):
'''return executed sql result to client.
post data format:
{"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."}
Returns:
sql result.
'''
## format sql
data = request.get_json()
options, sql_raw = dat... | python | {
"resource": ""
} |
q226742 | DashListData.get | train | def get(self, page=0, size=10):
"""Get dashboard meta info from in page `page` and page size is `size`.
Args:
page: page number.
size: size number.
Returns:
list of dict containing the dash_id and accordingly meta info.
maybe empty list [] when p... | python | {
"resource": ""
} |
q226743 | KeyList.get | train | def get(self):
"""Get key list in storage.
"""
keys = r_kv.keys()
keys.sort()
return build_response(dict(data=keys, code=200)) | python | {
"resource": ""
} |
q226744 | Key.get | train | def get(self, key):
"""Get a key-value from storage according to the key name.
"""
data = r_kv.get(key)
# data = json.dumps(data) if isinstance(data, str) else data
# data = json.loads(data) if data else {}
return build_response(dict(data=data, code=200)) | python | {
"resource": ""
} |
q226745 | Dash.get | train | def get(self, dash_id):
"""Just return the dashboard id in the rendering html.
JS will do other work [ajax and rendering] according to the dash_id.
Args:
dash_id: dashboard id.
Returns:
rendered html.
"""
return make_response(render_template('da... | python | {
"resource": ""
} |
q226746 | DashData.get | train | def get(self, dash_id):
"""Read dashboard content.
Args:
dash_id: dashboard id.
Returns:
A dict containing the content of that dashboard, not include the meta info.
"""
data = json.loads(r_db.hmget(config.DASH_CONTENT_KEY, dash_id)[0])
return bui... | python | {
"resource": ""
} |
q226747 | DashData.put | train | def put(self, dash_id=0):
"""Update a dash meta and content, return updated dash content.
Args:
dash_id: dashboard id.
Returns:
A dict containing the updated content of that dashboard, not include the meta info.
"""
data = request.get_json()
upda... | python | {
"resource": ""
} |
q226748 | DashData.delete | train | def delete(self, dash_id):
"""Delete a dash meta and content, return updated dash content.
Actually, just remove it to a specfied place in database.
Args:
dash_id: dashboard id.
Returns:
Redirect to home page.
"""
removed_info = dict(
... | python | {
"resource": ""
} |
q226749 | main | train | def main(
lang='deu', n=900, epochs=50, batch_size=64, num_neurons=256,
encoder_input_data=None,
decoder_input_data=None,
decoder_target_data=None,
checkpoint_dir=os.path.join(BIGDATA_PATH, 'checkpoints'),
):
""" Train an LSTM encoder-decoder squence-to-sequence model... | python | {
"resource": ""
} |
q226750 | BoltzmanMachine.energy | train | def energy(self, v, h=None):
"""Compute the global energy for the current joint state of all nodes
>>> q11_4 = BoltzmanMachine(bv=[0., 0.], bh=[-2.], Whh=np.zeros((1, 1)), Wvv=np.zeros((2, 2)), Wvh=[[3.], [-1.]])
>>> q11_4.configurations()
>>> v1v2h = product([0, 1], [0, 1], [0, 1])
... | python | {
"resource": ""
} |
q226751 | Hopfield.energy | train | def energy(self):
r""" Compute the global energy for the current joint state of all nodes
- sum(s[i] * b[i]) - sum([s[i]*s[j]*W[i,j] for (i, j) in product(range(N), range(N)) if i<j)])
E = − ∑ s i b i − ∑
i i< j
s i s j w ij
"""
s, b, W, N = self.state, self.b, ... | python | {
"resource": ""
} |
q226752 | HyperlinkStyleCorrector.translate | train | def translate(self, text, to_template='{name} ({url})', from_template=None, name_matcher=None, url_matcher=None):
""" Translate hyperinks into printable book style for Manning Publishing
>>> translator = HyperlinkStyleCorrector()
>>> adoc = 'See http://totalgood.com[Total Good] about that.'
... | python | {
"resource": ""
} |
q226753 | main | train | def main(dialogpath=None):
""" Parse the state transition graph for a set of dialog-definition tables to find an fix deadends """
if dialogpath is None:
args = parse_args()
dialogpath = os.path.abspath(os.path.expanduser(args.dialogpath))
else:
dialogpath = os.path.abspath(os.path.ex... | python | {
"resource": ""
} |
q226754 | prepare_data_maybe_download | train | def prepare_data_maybe_download(directory):
"""
Download and unpack dialogs if necessary.
"""
filename = 'ubuntu_dialogs.tgz'
url = 'http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz'
dialogs_path = os.path.join(directory, 'dialogs')
# test it there are some dialogs... | python | {
"resource": ""
} |
q226755 | fib | train | def fib(n):
"""Fibonacci example function
Args:
n (int): integer
Returns:
int: n-th Fibonacci number
"""
assert n > 0
a, b = 1, 1
for i in range(n - 1):
a, b = b, a + b
return a | python | {
"resource": ""
} |
q226756 | main | train | def main(args):
"""Main entry point allowing external calls
Args:
args ([str]): command line parameter list
"""
args = parse_args(args)
setup_logging(args.loglevel)
_logger.debug("Starting crazy calculations...")
print("The {}-th Fibonacci number is {}".format(args.n, fib(args.n)))
... | python | {
"resource": ""
} |
q226757 | optimize_feature_power | train | def optimize_feature_power(df, output_column_name=None, exponents=[2., 1., .8, .5, .25, .1, .01]):
""" Plot the correlation coefficient for various exponential scalings of input features
>>> np.random.seed(314159)
>>> df = pd.DataFrame()
>>> df['output'] = np.random.randn(1000)
>>> df['x10'] = df.o... | python | {
"resource": ""
} |
q226758 | representative_sample | train | def representative_sample(X, num_samples, save=False):
"""Sample vectors in X, preferring edge cases and vectors farthest from other vectors in sample set
"""
X = X.values if hasattr(X, 'values') else np.array(X)
N, M = X.shape
rownums = np.arange(N)
np.random.shuffle(rownums)
idx = Annoy... | python | {
"resource": ""
} |
q226759 | cosine_sim | train | def cosine_sim(vec1, vec2):
"""
Since our vectors are dictionaries, lets convert them to lists for easier mathing.
"""
vec1 = [val for val in vec1.values()]
vec2 = [val for val in vec2.values()]
dot_prod = 0
for i, v in enumerate(vec1):
dot_prod += v * vec2[i]
mag_1... | python | {
"resource": ""
} |
q226760 | LinearRegressor.fit | train | def fit(self, X, y):
""" Compute average slope and intercept for all X, y pairs
Arguments:
X (np.array): model input (independent variable)
y (np.array): model output (dependent variable)
Returns:
Linear Regression instance with `slope` and `intercept` attributes
... | python | {
"resource": ""
} |
q226761 | looks_like_url | train | def looks_like_url(url):
""" Simplified check to see if the text appears to be a URL.
Similar to `urlparse` but much more basic.
Returns:
True if the url str appears to be valid.
False otherwise.
>>> url = looks_like_url("totalgood.org")
>>> bool(url)
True
"""
if not isins... | python | {
"resource": ""
} |
q226762 | try_parse_url | train | def try_parse_url(url):
""" User urlparse to try to parse URL returning None on exception """
if len(url.strip()) < 4:
logger.info('URL too short: {}'.format(url))
return None
try:
parsed_url = urlparse(url)
except ValueError:
logger.info('Parse URL ValueError: {}'.format... | python | {
"resource": ""
} |
q226763 | get_url_filemeta | train | def get_url_filemeta(url):
""" Request HTML for the page at the URL indicated and return the url, filename, and remote size
TODO: just add remote_size and basename and filename attributes to the urlparse object
instead of returning a dict
>>> sorted(get_url_filemeta('mozilla.com').items())
[... | python | {
"resource": ""
} |
q226764 | save_response_content | train | def save_response_content(response, filename='data.csv', destination=os.path.curdir, chunksize=32768):
""" For streaming response from requests, download the content one CHUNK at a time """
chunksize = chunksize or 32768
if os.path.sep in filename:
full_destination_path = filename
else:
... | python | {
"resource": ""
} |
q226765 | download_file_from_google_drive | train | def download_file_from_google_drive(driveid, filename=None, destination=os.path.curdir):
""" Download script for google drive shared links
Thank you @turdus-merula and Andrew Hundt!
https://stackoverflow.com/a/39225039/623735
"""
if '&id=' in driveid:
# https://drive.google.com/uc?export=... | python | {
"resource": ""
} |
q226766 | find_greeting | train | def find_greeting(s):
""" Return the the greeting string Hi, Hello, or Yo if it occurs at the beginning of a string
>>> find_greeting('Hi Mr. Turing!')
'Hi'
>>> find_greeting('Hello, Rosa.')
'Hello'
>>> find_greeting("Yo, what's up?")
'Yo'
>>> find_greeting("Hello")
'Hello'
>>> ... | python | {
"resource": ""
} |
q226767 | file_to_list | train | def file_to_list(in_file):
''' Reads file into list '''
lines = []
for line in in_file:
# Strip new line
line = line.strip('\n')
# Ignore empty lines
if line != '':
# Ignore comments
if line[0] != '#':
lines.append(line)
return li... | python | {
"resource": ""
} |
q226768 | CompoundRule.add_flag_values | train | def add_flag_values(self, entry, flag):
''' Adds flag value to applicable compounds '''
if flag in self.flags:
self.flags[flag].append(entry) | python | {
"resource": ""
} |
q226769 | CompoundRule.get_regex | train | def get_regex(self):
''' Generates and returns compound regular expression '''
regex = ''
for flag in self.compound:
if flag == '?' or flag == '*':
regex += flag
else:
regex += '(' + '|'.join(self.flags[flag]) + ')'
return regex | python | {
"resource": ""
} |
q226770 | DICT.__parse_dict | train | def __parse_dict(self):
''' Parses dictionary with according rules '''
i = 0
lines = self.lines
for line in lines:
line = line.split('/')
word = line[0]
flags = line[1] if len(line) > 1 else None
# Base Word
self.num_words += ... | python | {
"resource": ""
} |
q226771 | load_imdb_df | train | def load_imdb_df(dirpath=os.path.join(BIGDATA_PATH, 'aclImdb'), subdirectories=(('train', 'test'), ('pos', 'neg', 'unsup'))):
""" Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings
Returns:
DataFrame: columns=['url', 'rating', 'text'], ... | python | {
"resource": ""
} |
q226772 | load_glove | train | def load_glove(filepath, batch_size=1000, limit=None, verbose=True):
r""" Load a pretrained GloVE word vector model
First header line of GloVE text file should look like:
400000 50\n
First vector of GloVE text file should look like:
the .12 .22 .32 .42 ... .42
>>> wv = load_glove(os.pa... | python | {
"resource": ""
} |
q226773 | load_glove_df | train | def load_glove_df(filepath, **kwargs):
""" Load a GloVE-format text file into a dataframe
>>> df = load_glove_df(os.path.join(BIGDATA_PATH, 'glove_test.txt'))
>>> df.index[:3]
Index(['the', ',', '.'], dtype='object', name=0)
>>> df.iloc[0][:3]
1 0.41800
2 0.24968
3 -0.41242
... | python | {
"resource": ""
} |
q226774 | get_en2fr | train | def get_en2fr(url='http://www.manythings.org/anki/fra-eng.zip'):
""" Download and parse English->French translation dataset used in Keras seq2seq example """
download_unzip(url)
return pd.read_table(url, compression='zip', header=None, skip_blank_lines=True, sep='\t', skiprows=0, names='en fr'.split()) | python | {
"resource": ""
} |
q226775 | load_anki_df | train | def load_anki_df(language='deu'):
""" Load into a DataFrame statements in one language along with their translation into English
>>> get_data('zsm').head(1)
eng zsm
0 Are you new? Awak baru?
"""
if os.path.isfile(langua... | python | {
"resource": ""
} |
q226776 | generate_big_urls_glove | train | def generate_big_urls_glove(bigurls=None):
""" Generate a dictionary of URLs for various combinations of GloVe training set sizes and dimensionality """
bigurls = bigurls or {}
for num_dim in (50, 100, 200, 300):
# not all of these dimensionality, and training set size combinations were trained by S... | python | {
"resource": ""
} |
q226777 | normalize_ext_rename | train | def normalize_ext_rename(filepath):
""" normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file
>>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt')
>>> pth == normalize_ext_rename(pth)
True
"""
logger.debug('normalize_ext.filepath=' + str(filepath)... | python | {
"resource": ""
} |
q226778 | untar | train | def untar(fname, verbose=True):
""" Uunzip and untar a tar.gz file into a subdir of the BIGDATA_PATH directory """
if fname.lower().endswith(".tar.gz"):
dirpath = os.path.join(BIGDATA_PATH, os.path.basename(fname)[:-7])
if os.path.isdir(dirpath):
return dirpath
with tarfile.o... | python | {
"resource": ""
} |
q226779 | endswith_strip | train | def endswith_strip(s, endswith='.txt', ignorecase=True):
""" Strip a suffix from the end of a string
>>> endswith_strip('http://TotalGood.com', '.COM')
'http://TotalGood'
>>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False)
'http://TotalGood.com'
"""
if ignorecase:
... | python | {
"resource": ""
} |
q226780 | startswith_strip | train | def startswith_strip(s, startswith='http://', ignorecase=True):
""" Strip a prefix from the beginning of a string
>>> startswith_strip('HTtp://TotalGood.com', 'HTTP://')
'TotalGood.com'
>>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False)
'HTtp://TotalGood.com'
"... | python | {
"resource": ""
} |
q226781 | get_longest_table | train | def get_longest_table(url='https://www.openoffice.org/dev_docs/source/file_extensions.html', header=0):
""" Retrieve the HTML tables from a URL and return the longest DataFrame found
>>> get_longest_table('https://en.wikipedia.org/wiki/List_of_sovereign_states').columns
Index(['Common and formal names', 'M... | python | {
"resource": ""
} |
q226782 | get_filename_extensions | train | def get_filename_extensions(url='https://www.webopedia.com/quick_ref/fileextensionsfull.asp'):
""" Load a DataFrame of filename extensions from the indicated url
>>> df = get_filename_extensions('https://www.openoffice.org/dev_docs/source/file_extensions.html')
>>> df.head(2)
ext ... | python | {
"resource": ""
} |
q226783 | create_big_url | train | def create_big_url(name):
""" If name looks like a url, with an http, add an entry for it in BIG_URLS """
# BIG side effect
global BIG_URLS
filemeta = get_url_filemeta(name)
if not filemeta:
return None
filename = filemeta['filename']
remote_size = filemeta['remote_size']
url = f... | python | {
"resource": ""
} |
q226784 | get_data | train | def get_data(name='sms-spam', nrows=None, limit=None):
""" Load data from a json, csv, or txt file if it exists in the data dir.
References:
[cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp)
[cities](http://download.geonames.org/export/dump/cities.zip)
[cities_us](ht... | python | {
"resource": ""
} |
q226785 | get_wikidata_qnum | train | def get_wikidata_qnum(wikiarticle, wikisite):
"""Retrieve the Query number for a wikidata database of metadata about a particular article
>>> print(get_wikidata_qnum(wikiarticle="Andromeda Galaxy", wikisite="enwiki"))
Q2469
"""
resp = requests.get('https://www.wikidata.org/w/api.php', timeout=5, pa... | python | {
"resource": ""
} |
q226786 | normalize_column_names | train | def normalize_column_names(df):
r""" Clean up whitespace in column names. See better version at `pugnlp.clean_columns`
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here'])
>>> normalize_column_names(df)
['hello_world', 'not_here']
"""
columns = df.columns if hasattr(df, ... | python | {
"resource": ""
} |
q226787 | clean_column_values | train | def clean_column_values(df, inplace=True):
r""" Convert dollar value strings, numbers with commas, and percents into floating point values
>>> df = get_data('us_gov_deficits_raw')
>>> df2 = clean_column_values(df, inplace=False)
>>> df2.iloc[0]
Fiscal year ... | python | {
"resource": ""
} |
q226788 | isglove | train | def isglove(filepath):
""" Get the first word vector in a GloVE file and return its dimensionality or False if not a vector
>>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt'))
False
"""
with ensure_open(filepath, 'r') as f:
header_line = f.readline()
vector_line = f.readline(... | python | {
"resource": ""
} |
q226789 | nlp | train | def nlp(texts, lang='en', linesep=None, verbose=True):
r""" Use the SpaCy parser to parse and tag natural language strings.
Load the SpaCy parser language model lazily and share it among all nlpia modules.
Probably unnecessary, since SpaCy probably takes care of this with `spacy.load()`
>>> _parse is ... | python | {
"resource": ""
} |
q226790 | get_decoder | train | def get_decoder(libdir=None, modeldir=None, lang='en-us'):
""" Create a decoder with the requested language model """
modeldir = modeldir or (os.path.join(libdir, 'model') if libdir else MODELDIR)
libdir = os.path.dirname(modeldir)
config = ps.Decoder.default_config()
config.set_string('-hmm', os.pa... | python | {
"resource": ""
} |
q226791 | transcribe | train | def transcribe(decoder, audio_file, libdir=None):
""" Decode streaming audio data from raw binary file on disk. """
decoder = get_decoder()
decoder.start_utt()
stream = open(audio_file, 'rb')
while True:
buf = stream.read(1024)
if buf:
decoder.process_raw(buf, False, Fal... | python | {
"resource": ""
} |
q226792 | pre_process_data | train | def pre_process_data(filepath):
"""
This is dependent on your training data source but we will try to generalize it as best as possible.
"""
positive_path = os.path.join(filepath, 'pos')
negative_path = os.path.join(filepath, 'neg')
pos_label = 1
neg_label = 0
dataset = []
for fil... | python | {
"resource": ""
} |
q226793 | pad_trunc | train | def pad_trunc(data, maxlen):
""" For a given dataset pad with zero vectors or truncate to maxlen """
new_data = []
# Create a vector of 0's the length of our word vectors
zero_vector = []
for _ in range(len(data[0][0])):
zero_vector.append(0.0)
for sample in data:
if len(sampl... | python | {
"resource": ""
} |
q226794 | clean_data | train | def clean_data(data):
""" Shift to lower case, replace unknowns with UNK, and listify """
new_data = []
VALID = 'abcdefghijklmnopqrstuvwxyz123456789"\'?!.,:; '
for sample in data:
new_sample = []
for char in sample[1].lower(): # Just grab the string, not the label
if char in... | python | {
"resource": ""
} |
q226795 | char_pad_trunc | train | def char_pad_trunc(data, maxlen):
""" We truncate to maxlen or add in PAD tokens """
new_dataset = []
for sample in data:
if len(sample) > maxlen:
new_data = sample[:maxlen]
elif len(sample) < maxlen:
pads = maxlen - len(sample)
new_data = sample + ['PAD']... | python | {
"resource": ""
} |
q226796 | create_dicts | train | def create_dicts(data):
""" Modified from Keras LSTM example"""
chars = set()
for sample in data:
chars.update(set(sample))
char_indices = dict((c, i) for i, c in enumerate(chars))
indices_char = dict((i, c) for i, c in enumerate(chars))
return char_indices, indices_char | python | {
"resource": ""
} |
q226797 | onehot_encode | train | def onehot_encode(dataset, char_indices, maxlen):
"""
One hot encode the tokens
Args:
dataset list of lists of tokens
char_indices dictionary of {key=character, value=index to use encoding vector}
maxlen int Length of each sample
Return:
np array of shape (samples, ... | python | {
"resource": ""
} |
q226798 | _fit_full | train | def _fit_full(self=self, X=X, n_components=6):
"""Fit the model by computing full SVD on X"""
n_samples, n_features = X.shape
# Center data
self.mean_ = np.mean(X, axis=0)
print(self.mean_)
X -= self.mean_
print(X.round(2))
U, S, V = linalg.svd(X, full_matrices=False)
print(V.round... | python | {
"resource": ""
} |
q226799 | extract_aiml | train | def extract_aiml(path='aiml-en-us-foundation-alice.v1-9'):
""" Extract an aiml.zip file if it hasn't been already and return a list of aiml file paths """
path = find_data_path(path) or path
if os.path.isdir(path):
paths = os.listdir(path)
paths = [os.path.join(path, p) for p in paths]
e... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.