Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _normalize_data(stream, date_format=None):
"""
This function is meant to normalize data for upload to the Luminoso
Analytics system. Currently it only normalizes dates.
If date_format is not specified, or if there's no date in a particular doc,
the the doc is yielded unchanged.
"""
for ... |
def _convert_date(date_string, date_format):
"""
Convert a date in a given format to epoch time. Mostly a wrapper for
datetime's strptime.
"""
if date_format != 'epoch':
return datetime.strptime(date_string, date_format).timestamp()
else:
return float(date_string) |
def detect_file_encoding(filename):
"""
Use ftfy to detect the encoding of a file, based on a sample of its
first megabyte.
ftfy's encoding detector is limited. The only encodings it can detect are
UTF-8, CESU-8, UTF-16, Windows-1252, and occasionally MacRoman. But it
does much better than char... |
def stream_json_lines(file):
"""
Load a JSON stream and return a generator, yielding one object at a time.
"""
if isinstance(file, string_type):
file = open(file, 'rb')
for line in file:
line = line.strip()
if line:
if isinstance(line, bytes):
line... |
def transcode_to_utf8(filename, encoding):
"""
Convert a file in some other encoding into a temporary file that's in
UTF-8.
"""
tmp = tempfile.TemporaryFile()
for line in io.open(filename, encoding=encoding):
tmp.write(line.strip('\uFEFF').encode('utf-8'))
tmp.seek(0)
return tmp |
def open_csv_somehow_py2(filename):
"""
Open a CSV file using Python 2's CSV module, working around the deficiency
where it can't handle the null bytes of UTF-16.
"""
encoding = detect_file_encoding(filename)
if encoding.startswith('UTF-16'):
csvfile = transcode_to_utf8(filename, encodin... |
def _read_csv(reader, header, encode_fn):
"""
Given a constructed CSV reader object, a header row that we've read, and
a detected encoding, yield its rows as dictionaries.
"""
for row in reader:
if len(row) == 0:
continue
row = [encode_fn(cell) for cell in row]
ro... |
def main():
"""
Handle command line arguments to convert a file to a JSON stream as a
script.
"""
logging.basicConfig(level=logging.INFO)
import argparse
parser = argparse.ArgumentParser(
description="Translate CSV or JSON input to a JSON stream, or verify "
"some... |
def jsonify_parameters(params):
"""
When sent in an authorized REST request, only strings and integers can be
transmitted accurately. Other types of data need to be encoded into JSON.
"""
result = {}
for param, value in params.items():
if isinstance(value, (int, str)):
result... |
def connect(cls, url=None, token_file=None, token=None):
"""
Returns an object that makes requests to the API, authenticated
with a saved or specified long-lived token, at URLs beginning with
`url`.
If no URL is specified, or if the specified URL is a path such as
'/proj... |
def save_token(token, domain='analytics.luminoso.com', token_file=None):
"""
Take a long-lived API token and store it to a local file. Long-lived
tokens can be retrieved through the UI. Optional arguments are the
domain for which the token is valid and the file in which to store the
... |
def connect_with_username_and_password(cls, url=None, username=None,
password=None):
"""
Returns an object that makes requests to the API, authenticated with
a short-lived token retrieved from username and password. If username
or password is n... |
def _request(self, req_type, url, **kwargs):
"""
Make a request via the `requests` module. If the result has an HTTP
error status, convert that to a Python exception.
"""
logger.debug('%s %s' % (req_type, url))
result = self.session.request(req_type, url, **kwargs)
... |
def post(self, path='', **params):
"""
Make a POST request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to form values, sent in the body
of the POST.
POST requests are requests that cause a change on the server,
esp... |
def delete(self, path='', **params):
"""
Make a DELETE request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to URL parameters.
DELETE requests ask to delete the object represented by this URL.
"""
params = jsonify_p... |
def client_for_path(self, path):
"""
Returns a new client with the same root URL and authentication, but
a different specific URL. For instance, if you have a client pointed
at https://analytics.luminoso.com/api/v5/, and you want new ones for
Project A and Project B, you would c... |
def upload(self, path, docs, **params):
"""
A deprecated alias for post(path, docs=docs), included only for
backward compatibility.
"""
logger.warning('The upload method is deprecated; use post instead.')
return self.post(path, docs=docs) |
def wait_for_build(self, interval=5, path=None):
"""
A convenience method designed to inform you when a project build has
completed. It polls the API every `interval` seconds until there is
not a build running. At that point, it returns the "last_build_info"
field of the projec... |
def save_to_file(self, path, filename, **params):
"""
Saves binary content to a file with name filename. filename should
include the appropriate file extension, such as .xlsx or .txt, e.g.,
filename = 'sample.xlsx'.
Useful for downloading .xlsx files.
"""
url = e... |
def get_root_url(url, warn=True):
"""
Get the "root URL" for a URL, as described in the LuminosoClient
documentation.
"""
parsed_url = urlparse(url)
# Make sure it's a complete URL, not a relative one
if not parsed_url.scheme:
raise ValueError('Please supply a full URL, beginning wi... |
def jsonify_parameters(params):
"""
When sent in an authorized REST request, only strings and integers can be
transmitted accurately. Other types of data need to be encoded into JSON.
"""
result = {}
for param, value in params.items():
if isinstance(value, types_not_to_encode):
... |
def connect(cls, url=None, username=None, password=None, token=None,
token_file=None):
"""
Returns an object that makes requests to the API, authenticated
with the provided username/password, at URLs beginning with `url`.
You can leave out the URL and get your 'default U... |
def save_token(self, token_file=None):
"""
Obtain the user's long-lived API token and save it in a local file.
If the user has no long-lived API token, one will be created.
Returns the token that was saved.
"""
tokens = self._json_request('get', self.root_url + '/user/tok... |
def _json_request(self, req_type, url, **kwargs):
"""
Make a request of the specified type and expect a JSON object in
response.
If the result has an 'error' value, raise a LuminosoAPIError with
its contents. Otherwise, return the contents of the 'result' value.
"""
... |
def post(self, path='', **params):
"""
Make a POST request to the given path, and return the JSON-decoded
result.
Keyword parameters will be converted to form values, sent in the body
of the POST.
POST requests are requests that cause a change on the server,
esp... |
def post_data(self, path, data, content_type, **params):
"""
Make a POST request to the given path, with `data` in its body.
Return the JSON-decoded result.
The content_type must be set to reflect the kind of data being sent,
which is often `application/json`.
Keyword p... |
def change_path(self, path):
"""
Return a new LuminosoClient for a subpath of this one.
For example, you might want to start with a LuminosoClient for
`https://analytics.luminoso.com/api/v4/`, then get a new one for
`https://analytics.luminoso.com/api/v4/projects/myaccount/mypro... |
def _get_default_account(self):
"""
Get the ID of an account you can use to access projects.
"""
newclient = self.__class__(self.session, self.root_url)
account_info = newclient.get('/accounts/')
if account_info['default_account'] is not None:
return account_i... |
def documentation(self):
"""
Get the documentation that the server sends for the API.
"""
newclient = self.__class__(self.session, self.root_url)
return newclient.get_raw('/') |
def upload(self, path, docs, **params):
"""
A convenience method for uploading a set of dictionaries representing
documents. You still need to specify the URL to upload to, which will
look like ROOT_URL/projects/myaccount/project_id/docs.
"""
json_data = json.dumps(list(d... |
def wait_for(self, job_id, base_path=None, interval=5):
"""
Wait for an asynchronous task to finish.
Unlike the thin methods elsewhere on this object, this one is actually
specific to how the Luminoso API works. This will poll an API
endpoint to find out the status of the job nu... |
def get_raw(self, path, **params):
"""
Get the raw text of a response.
This is only generally useful for specific URLs, such as documentation.
"""
url = ensure_trailing_slash(self.url + path.lstrip('/'))
return self._request('get', url, params=params).text |
def _print_csv(result):
"""Print a JSON list of JSON objects in CSV format."""
if type(result) is not list:
raise TypeError("output not able to be displayed as CSV.")
first_line = result[0]
w = csv.DictWriter(sys.stdout, fieldnames=sorted(first_line.keys()))
w.writeheader()
for line in r... |
def _read_params(input_file, json_body, p_params):
"""Read parameters from input file, -j, and -p arguments, in that order."""
params = {}
try:
if input_file:
params.update(json.load(input_file))
if json_body is not None:
params.update(json.loads(json_body))
excep... |
def _batches(iterable, size):
"""
Take an iterator and yield its contents in groups of `size` items.
"""
sourceiter = iter(iterable)
while True:
try:
batchiter = islice(sourceiter, size)
yield chain([next(batchiter)], batchiter)
except StopIteration:
... |
def _simplify_doc(doc):
"""
Limit a document to just the three fields we should upload.
"""
# Mutate a copy of the document to fill in missing fields
doc = dict(doc)
if 'text' not in doc:
raise ValueError("The document {!r} has no text field".format(doc))
return {
'text': doc... |
def create_project_with_docs(
client, docs, language, name, account=None, progress=False
):
"""
Given an iterator of documents, upload them as a Luminoso project.
"""
description = 'Uploaded using lumi-upload at {}'.format(time.asctime())
if account is not None:
proj_record = client.post... |
def upload_docs(
client, input_filename, language, name, account=None, progress=False
):
"""
Given a LuminosoClient pointing to the root of the API, and a filename to
read JSON lines from, create a project from the documents in that file.
"""
docs = iterate_json_lines(input_filename)
return ... |
def _main(argv):
"""
Handle arguments for the 'lumi-upload' command.
"""
parser = argparse.ArgumentParser(
description=DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
'-b',
'--base-url',
default=URL_BASE,
h... |
def batches(iterable, size):
"""
Take an iterator and yield its contents in groups of `size` items.
"""
sourceiter = iter(iterable)
while True:
batchiter = islice(sourceiter, size)
yield chain([next(batchiter)], batchiter) |
def upload_stream(stream, server, account, projname, language=None,
username=None, password=None,
append=False, stage=False):
"""
Given a file-like object containing a JSON stream, upload it to
Luminoso with the given account name and project name.
"""
client = Lu... |
def upload_file(filename, server, account, projname, language=None,
username=None, password=None,
append=False, stage=False, date_format=None):
"""
Upload a file to Luminoso with the given account and project name.
Given a file containing JSON, JSON stream, or CSV data, this... |
def main():
"""
Handle command line arguments, to upload a file to a Luminoso project
as a script.
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('filename')
parser.add_argument('account')
parser.add_argument('project_name')
parser.add_argument(
... |
def from_user_creds(cls, username, password, url=URL_BASE):
"""
Obtain a short-lived token using a username and password, and use that
token to create an auth object.
"""
session = requests.session()
token_resp = session.post(url.rstrip('/') + '/user/login/',
... |
def login(self):
"""Set http session."""
if self._session is None:
self._session = requests.session()
# adding fake user-agent header
self._session.headers.update({'User-agent': str(UserAgent().random)})
return self._post_login_page() |
def _post_login_page(self):
"""Login to enedis."""
data = {
'IDToken1': self.username,
'IDToken2': self.password,
'SunQueryParamsString': base64.b64encode(b'realm=particuliers'),
'encoded': 'true',
'gx_charset': 'UTF-8'
}
try:
... |
def _get_data(self, p_p_resource_id, start_date=None, end_date=None):
"""Get data."""
data = {
'_' + REQ_PART + '_dateDebut': start_date,
'_' + REQ_PART + '_dateFin': end_date
}
params = {
'p_p_id': REQ_PART,
'p_p_lifecycle': 2,
... |
def fetch_data(self):
"""Get the latest data from Enedis."""
for t in [HOURLY, DAILY, MONTHLY, YEARLY]:
self._data[t] = self.get_data_per_period(t) |
def main():
"""Main function"""
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--username',
required=True, help='enedis username')
parser.add_argument('-p', '--password',
required=True, help='Password')
args = parser.parse_args()
cl... |
def prepare(self):
""" Load the view on first load """
if self.__class__.view:
return
#: Load the View class from the dotted view name
with enaml.imports():
View = pydoc.locate(self.page.view)
assert View, "Failed to import View: {}".format(self.p... |
def initialize(self):
""" Load the view on first load could also load based on session, group, etc..
"""
if self.__class__.view:
self.view.handler = self
self.view.request = self.request
return
#: Load the View class from the dotted view name... |
def get(self, *args, **kwargs):
#: Render view for get request, view is cached for websocket
""" Execute the correct handler depending on what is connecting. """
if self.is_websocket():
return super(DemoHandler, self).get(*args, **kwargs)
else:
#return tornado.web... |
def on_message(self, message):
""" When enaml.js sends a message """
#: Decode message
change = tornado.escape.json_decode(message)
#print change
#: Get the owner ID
ref = change.get('ref')
if not ref:
return
#: Get the server side rep... |
def _update_menus(self,change):
""" When pages change, update the menus"""
menus = {}
#: Get all links
links = [p.link for p in self.pages if p.link] + self.links
#: Put all links in the correct menu
for link in links:
for menu in link.menus... |
def _default_handlers(self):
""" Generate the handlers for this site """
static_path = os.path.abspath(os.path.join(os.path.dirname(__file__),"static"))
urls = [
(r"/static/(.*)", cyclone.web.StaticFileHandler, {"path": static_path}),
]
for p in self.pages:
... |
def on_message(self, message):
""" When we get an event from js, lookup the node and invoke the
action on the enaml node.
"""
change = json.loads(message)
log.debug(f'Update from js: {change}')
# Lookup the node
ref = change.get('ref')
if not ref:
... |
def on_dom_modified(self, change):
""" When an event from enaml occurs, send it out the websocket
so the client's browser can update accordingly.
"""
log.debug(f'Update from enaml: {change}')
self.write_message(json.dumps(change['value'])) |
def create_widget(self):
""" Create the toolkit widget for the proxy object.
This method is called during the top-down pass, just before the
'init_widget()' method is called. This method should create the
toolkit widget and assign it to the 'widget' attribute.
"""
self.... |
def init_widget(self):
""" Initialize the state of the toolkit widget.
This method is called during the top-down pass, just after the
'create_widget()' method is called. This method should init the
state of the widget. The child widgets will not yet be created.
"""
widg... |
def destroy(self):
""" A reimplemented destructor.
This destructor will clear the reference to the toolkit widget
and set its parent to None.
"""
widget = self.widget
if widget is not None:
parent = widget.getparent()
if parent is not None:
... |
def child_added(self, child):
""" Handle the child added event from the declaration.
This handler will insert the child toolkit widget in the correct.
position. Subclasses which need more control should reimplement this
method.
"""
super(WebComponent, self).child_added(... |
def child_removed(self, child):
""" Handle the child removed event from the declaration.
This handler will unparent the child toolkit widget. Subclasses
which need more control should reimplement this method.
"""
super(WebComponent, self).child_removed(child)
if child.w... |
def find(self, query, **kwargs):
""" Get the node(s) matching the query"""
nodes = self.widget.xpath(query, **kwargs)
if not nodes:
return []
matches = []
for node in nodes:
aref = CACHE.get(node.attrib.get('ref'))
obj = aref() if aref else Non... |
def child_widgets(self):
""" Get the child toolkit widgets for this object.
Returns
-------
result : iterable of QObject
The child widgets defined for this object.
"""
for child in self.children():
w = child.widget
if w is not None:
... |
def set_attribute(self, name, value):
""" Default handler for those not explicitly defined """
if value is True:
self.widget.set(name, name)
elif value is False:
del self.widget.attrib[name]
else:
self.widget.set(name, str(value)) |
def _update_proxy(self, change):
""" Update the proxy widget when the Widget data
changes.
"""
#: Try default handler
if change['type'] == 'update' and self.proxy_is_active:
handler = getattr(self.proxy, 'set_' + change['name'], None)
if handler is not Non... |
def _notify_modified(self, change):
""" If a change occurs when we have a websocket connection active
notify the websocket client of the change.
"""
root = self.root_object()
if isinstance(root, Html):
name = change['name']
change = {
'ref... |
def xpath(self, query, **kwargs):
""" Find nodes matching the given xpath query """
nodes = self.proxy.find(query, **kwargs)
return [n.declaration for n in nodes] |
def prepare(self, **kwargs):
""" Prepare for rendering """
for k, v in kwargs.items():
setattr(self, k, v)
if not self.is_initialized:
self.initialize()
if not self.proxy_is_active:
self.activate_proxy() |
def init_widget(self):
""" Initialize the widget with the source. """
d = self.declaration
if d.source:
self.set_source(d.source)
else:
super(RawComponent, self).init_widget() |
def set_source(self, source):
""" Set the source by parsing the source and inserting it into the
component.
"""
self.widget.clear()
html = etree.HTML(source)
self.widget.extend(html[0])
# Clear removes everything so it must be reinitialized
super(RawCom... |
def _observe_mode(self, change):
""" If the mode changes. Refresh the items.
"""
block = self.block
if block and self.is_initialized and change['type'] == 'update':
if change['oldvalue'] == 'replace':
raise NotImplementedError
for c in sel... |
def _observe_block(self, change):
""" A change handler for the 'objects' list of the Include.
If the object is initialized objects which are removed will be
unparented and objects which are added will be reparented. Old
objects will be destroyed if the 'destroy_old' flag is True.
... |
def _observe__children(self, change):
""" When the children of the block change. Update the referenced
block.
"""
if not self.is_initialized or change['type'] != 'update':
return
block = self.block
new_children = change['value']
old_children ... |
def read(*pathcomponents):
"""Read the contents of a file located relative to setup.py"""
with open(join(abspath(dirname(__file__)), *pathcomponents)) as thefile:
return thefile.read() |
def print_obj(obj, verbose, metadata, mongo_version):
"""
Print the dict returned by a MongoDB Query in the standard output.
"""
if verbose:
sys.stdout.write(json_encoder.encode(obj) + '\n')
sys.stdout.flush()
else:
try:
ts_time = obj['ts']
operation =... |
def connect(address, args):
"""
Connect with `address`, and return a tuple with a :class:`~pymongo.MongoClient`,
and a :class:`~pymongo.database.Database` object.
:param address: a string representation with the db address
:param args: connection arguments:
- username: username for authenticatio... |
def error(msg, exit_code):
"""
Print `msg` error and exit with status `exit_code`
"""
sys.stderr.write("%s\ntry 'mongotail --help' for more information\n" % msg)
sys.stderr.flush()
exit(exit_code) |
def error_parsing(msg="unknown options"):
"""
Print any parsing error and exit with status -1
"""
sys.stderr.write("Error parsing command line: %s\ntry 'mongotail --help' for more information\n" % msg)
sys.stderr.flush()
exit(EINVAL) |
def get_product_by_name(self, name):
'''
Gets a Item from the Menu by name. Note that the name is not
case-sensitive but must be spelt correctly.
:param string name: The name of the item.
:raises StopIteration: Raises exception if no item is found.
:return: An item objec... |
def new_session(self, session):
'''
Clear out the current session on the remote and setup a new one.
:return: A response from having expired the current session.
:rtype: requests.Response
'''
response = self.__get('/Home/SessionExpire')
self.session = update_sess... |
def reset_store(self):
'''
Clears out the current store and gets a cookie. Set the cross site
request forgery token for each subsequent request.
:return: A response having cleared the current store.
:rtype: requests.Response
'''
response = self.__get('/Store/Rese... |
def get_stores(self, search_term):
'''
Search for dominos pizza stores using a search term.
:param string search: Search term.
:return: A list of nearby stores matching the search term.
:rtype: list
'''
params = {'SearchText': search_term}
response = self... |
def set_delivery_system(self, store, postcode, fulfilment_method=FULFILMENT_METHOD.DELIVERY):
'''
Set local cookies by initialising the delivery system on the remote.
Requires a store ID and a delivery postcode.
:param Store store: Store id.
:param string postcode: A postcode.
... |
def get_menu(self, store):
'''
Retrieve the menu from the selected store.
:param Store store: A store.
:return: The store menu.
:rtype: Menu
'''
params = {
'collectionOnly': not store.delivery_available,
'menuVersion': store.menu_version,
... |
def add_item_to_basket(self, item, variant=VARIANT.MEDIUM, quantity=1):
'''
Add an item to the current basket.
:param Item item: Item from menu.
:param int variant: Item SKU id. Ignored if the item is a side.
:param int quantity: The quantity of item to be added.
:return... |
def add_pizza_to_basket(self, item, variant=VARIANT.MEDIUM, quantity=1):
'''
Add a pizza to the current basket.
:param Item item: Item from menu.
:param int variant: Item SKU id. Some defaults are defined in the VARIANT enum.
:param int quantity: The quantity of pizza to be adde... |
def add_side_to_basket(self, item, quantity=1):
'''
Add a side to the current basket.
:param Item item: Item from menu.
:param int quantity: The quantity of side to be added.
:return: A response having added a side to the current basket.
:rtype: requests.Response
... |
def remove_item_from_basket(self, idx):
'''
Remove an item from the current basket.
:param int idx: Basket item id.
:return: A response having removed an item from the current basket.
:rtype: requests.Response
'''
params = {
'basketItemId': idx,
... |
def set_payment_method(self, method=PAYMENT_METHOD.CASH_ON_DELIVERY):
'''
Select the payment method going to be used to make a purchase.
:param int method: Payment method id.
:return: A response having set the payment option.
:rtype: requests.Response
'''
params ... |
def process_payment(self):
'''
Proceed with payment using the payment method selected earlier.
:return: A response having processes the payment.
:rtype: requests.Response
'''
params = {
'__RequestVerificationToken': self.session.cookies,
'method':... |
def __get(self, path, **kargs):
'''
Make a HTTP GET request to the Dominos UK API with the given parameters
for the current session.
:param string path: The API endpoint path.
:params list kargs: A list of arguments.
:return: A response from the Dominos UK API.
:... |
def __post(self, path, **kargs):
'''
Make a HTTP POST request to the Dominos UK API with the given
parameters for the current session.
:param string path: The API endpoint path.
:params list kargs: A list of arguments.
:return: A response from the Dominos UK API.
... |
def __call_api(self, verb, path, **kargs):
'''
Make a HTTP request to the Dominos UK API with the given parameters for
the current session.
:param verb func: HTTP method on the session.
:param string path: The API endpoint path.
:params list kargs: A list of arguments.
... |
def append_item(self, item):
"""
Add an item to the end of the menu before the exit item
:param MenuItem item: The item to be added
"""
did_remove = self.remove_exit()
item.menu = self
self.items.append(item)
if did_remove:
self.add_exit()
... |
def add_exit(self):
"""
Add the exit item if necessary. Used to make sure there aren't multiple exit items
:return: True if item needed to be added, False otherwise
:rtype: bool
"""
if self.items:
if self.items[-1] is not self.exit_item:
self.... |
def draw(self):
"""
Redraws the menu and refreshes the screen. Should be called whenever something changes that needs to be redrawn.
"""
self.screen.border(0)
if self.title is not None:
self.screen.addstr(2, 2, self.title, curses.A_STANDOUT)
if self.subtitle ... |
def process_user_input(self):
"""
Gets the next single character and decides what to do with it
"""
user_input = self.get_input()
go_to_max = ord("9") if len(self.items) >= 9 else ord(str(len(self.items)))
if ord('1') <= user_input <= go_to_max:
self.go_to(u... |
def select(self):
"""
Select the current item and run it
"""
self.selected_option = self.current_option
self.selected_item.set_up()
self.selected_item.action()
self.selected_item.clean_up()
self.returned_value = self.selected_item.get_return()
self... |
def show(self, index):
"""
This class overrides this method
"""
if self.menu and self.menu.parent:
self.text = "Return to %s menu" % self.menu.parent.title
else:
self.text = "Exit"
return super(ExitItem, self).show(index) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.