sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def start_engine(self, **kwargs):
"""
Initializes the workflow with given request, response objects and diagram name.
Args:
session:
input:
workflow_name (str): Name of workflow diagram without ".bpmn" suffix.
File must be placed under one of con... | Initializes the workflow with given request, response objects and diagram name.
Args:
session:
input:
workflow_name (str): Name of workflow diagram without ".bpmn" suffix.
File must be placed under one of configured :py:attr:`~zengine.settings.WORKFLOW_PACKAGES_... | entailment |
def generate_wf_state_log(self):
"""
Logs the state of workflow and content of task_data.
"""
output = '\n- - - - - -\n'
output += "WORKFLOW: %s ( %s )" % (self.current.workflow_name.upper(),
self.current.workflow.name)
output +... | Logs the state of workflow and content of task_data. | entailment |
def switch_from_external_to_main_wf(self):
"""
Main workflow switcher.
This method recreates main workflow from `main wf` dict which
was set by external workflow swicther previously.
"""
# in external assigned as True in switch_to_external_wf.
# external_wf sh... | Main workflow switcher.
This method recreates main workflow from `main wf` dict which
was set by external workflow swicther previously. | entailment |
def switch_to_external_wf(self):
"""
External workflow switcher.
This method copies main workflow information into
a temporary dict `main_wf` and makes external workflow
acting as main workflow.
"""
# External WF name should be stated at main wf diagram and typ... | External workflow switcher.
This method copies main workflow information into
a temporary dict `main_wf` and makes external workflow
acting as main workflow. | entailment |
def _clear_current_task(self):
"""
Clear tasks related attributes, checks permissions
While switching WF to WF, authentication and permissions are checked for new WF.
"""
self.current.task_name = None
self.current.task_type = None
self.current.task = None | Clear tasks related attributes, checks permissions
While switching WF to WF, authentication and permissions are checked for new WF. | entailment |
def run(self):
"""
Main loop of the workflow engine
- Updates ::class:`~WFCurrent` object.
- Checks for Permissions.
- Activates all READY tasks.
- Runs referenced activities (method calls).
- Saves WF states.
- Stops if current task is a UserTask or EndT... | Main loop of the workflow engine
- Updates ::class:`~WFCurrent` object.
- Checks for Permissions.
- Activates all READY tasks.
- Runs referenced activities (method calls).
- Saves WF states.
- Stops if current task is a UserTask or EndTask.
- Deletes state object... | entailment |
def check_for_rerun_user_task(self):
"""
Checks that the user task needs to re-run.
If necessary, current task and pre task's states are changed and re-run.
If wf_meta not in data(there is no user interaction from pre-task) and last completed task
type is user task and current st... | Checks that the user task needs to re-run.
If necessary, current task and pre task's states are changed and re-run.
If wf_meta not in data(there is no user interaction from pre-task) and last completed task
type is user task and current step is not EndEvent and there is no lane change,
t... | entailment |
def switch_lang(self):
"""Switch to the language of the current user.
If the current language is already the specified one, nothing will be done.
"""
locale = self.current.locale
translation.InstalledLocale.install_language(locale['locale_language'])
translation.Installe... | Switch to the language of the current user.
If the current language is already the specified one, nothing will be done. | entailment |
def catch_lane_change(self):
"""
trigger a lane_user_change signal if we switched to a new lane
and new lane's user is different from current one
"""
if self.current.lane_name:
if self.current.old_lane and self.current.lane_name != self.current.old_lane:
... | trigger a lane_user_change signal if we switched to a new lane
and new lane's user is different from current one | entailment |
def parse_workflow_messages(self):
"""
Transmits client message that defined in
a workflow task's inputOutput extension
.. code-block:: xml
<bpmn2:extensionElements>
<camunda:inputOutput>
<camunda:inputParameter name="client_message">
<cam... | Transmits client message that defined in
a workflow task's inputOutput extension
.. code-block:: xml
<bpmn2:extensionElements>
<camunda:inputOutput>
<camunda:inputParameter name="client_message">
<camunda:map>
<camunda:entry key="title">Teşe... | entailment |
def run_activity(self):
"""
runs the method that referenced from current task
"""
activity = self.current.activity
if activity:
if activity not in self.wf_activities:
self._load_activity(activity)
self.current.log.debug(
"Ca... | runs the method that referenced from current task | entailment |
def _import_object(self, path, look_for_cls_method):
"""
Imports the module that contains the referenced method.
Args:
path: python path of class/function
look_for_cls_method (bool): If True, treat the last part of path as class method.
Returns:
Tupl... | Imports the module that contains the referenced method.
Args:
path: python path of class/function
look_for_cls_method (bool): If True, treat the last part of path as class method.
Returns:
Tuple. (class object, class name, method to be called) | entailment |
def _load_activity(self, activity):
"""
Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path.
"""
fpths = []
full_path = ''
errors = []
paths = settings.ACTIVITY_MODULES_IMPORT_PATHS
number_of_paths = len... | Iterates trough the all enabled `~zengine.settings.ACTIVITY_MODULES_IMPORT_PATHS` to find the given path. | entailment |
def check_for_authentication(self):
"""
Checks current workflow against :py:data:`~zengine.settings.ANONYMOUS_WORKFLOWS` list.
Raises:
HTTPUnauthorized: if WF needs an authenticated user and current user isn't.
"""
auth_required = self.current.workflow_name not in se... | Checks current workflow against :py:data:`~zengine.settings.ANONYMOUS_WORKFLOWS` list.
Raises:
HTTPUnauthorized: if WF needs an authenticated user and current user isn't. | entailment |
def check_for_lane_permission(self):
"""
One or more permissions can be associated with a lane
of a workflow. In a similar way, a lane can be
restricted with relation to other lanes of the workflow.
This method called on lane changes and checks user has
required permissi... | One or more permissions can be associated with a lane
of a workflow. In a similar way, a lane can be
restricted with relation to other lanes of the workflow.
This method called on lane changes and checks user has
required permissions and relations.
Raises:
HTTPForb... | entailment |
def check_for_permission(self):
# TODO: Works but not beautiful, needs review!
"""
Checks if current user (or role) has the required permission
for current workflow step.
Raises:
HTTPError: if user doesn't have required permissions.
"""
if self.curren... | Checks if current user (or role) has the required permission
for current workflow step.
Raises:
HTTPError: if user doesn't have required permissions. | entailment |
def handle_wf_finalization(self):
"""
Removes the ``token`` key from ``current.output`` if WF is over.
"""
if ((not self.current.flow_enabled or (
self.current.task_type.startswith('End') and not self.are_we_in_subprocess())) and
'token' in self.current.ou... | Removes the ``token`` key from ``current.output`` if WF is over. | entailment |
def from_rdkit_molecule(data):
"""
RDKit molecule object to MoleculeContainer converter
"""
m = MoleculeContainer()
atoms, mapping = [], []
for a in data.GetAtoms():
atom = {'element': a.GetSymbol(), 'charge': a.GetFormalCharge()}
atoms.append(atom)
mapping.append(a.GetAt... | RDKit molecule object to MoleculeContainer converter | entailment |
def to_rdkit_molecule(data):
"""
MoleculeContainer to RDKit molecule object converter
"""
mol = RWMol()
conf = Conformer()
mapping = {}
is_3d = False
for n, a in data.atoms():
ra = Atom(a.number)
ra.SetAtomMapNum(n)
if a.charge:
ra.SetFormalCharge(a.ch... | MoleculeContainer to RDKit molecule object converter | entailment |
def __dfs(self, start, weights, depth_limit):
"""
modified NX dfs
"""
adj = self._adj
stack = [(start, depth_limit, iter(sorted(adj[start], key=weights)))]
visited = {start}
disconnected = defaultdict(list)
edges = defaultdict(list)
while stack:
... | modified NX dfs | entailment |
def get_args_parser():
"""Return a parser for command line options."""
parser = argparse.ArgumentParser(
description='Marabunta: Migrating ants for Odoo')
parser.add_argument('--migration-file', '-f',
action=EnvDefault,
envvar='MARABUNTA_MIGRATION_FILE... | Return a parser for command line options. | entailment |
def from_parse_args(cls, args):
"""Constructor from command line args.
:param args: parse command line arguments
:type args: argparse.ArgumentParser
"""
return cls(args.migration_file,
args.database,
db_user=args.db_user,
... | Constructor from command line args.
:param args: parse command line arguments
:type args: argparse.ArgumentParser | entailment |
def set_current(self, current):
"""
Creates some aliases for attributes of ``current``.
Args:
current: :attr:`~zengine.engine.WFCurrent` object.
"""
self.current = current
self.input = current.input
# self.req = current.request
# self.resp = c... | Creates some aliases for attributes of ``current``.
Args:
current: :attr:`~zengine.engine.WFCurrent` object. | entailment |
def form_out(self, _form=None):
"""
Renders form. Applies form modifiers, then writes
result to response payload. If supplied, given form
object instance will be used instead of view's
default ObjectForm.
Args:
_form (:py:attr:`~zengine.forms.json_form.JsonF... | Renders form. Applies form modifiers, then writes
result to response payload. If supplied, given form
object instance will be used instead of view's
default ObjectForm.
Args:
_form (:py:attr:`~zengine.forms.json_form.JsonForm`):
Form object to override `self.o... | entailment |
def set_client_cmd(self, *args):
"""
Adds given cmd(s) to ``self.output['client_cmd']``
Args:
*args: Client commands.
"""
self.client_cmd.update(args)
self.output['client_cmd'] = list(self.client_cmd) | Adds given cmd(s) to ``self.output['client_cmd']``
Args:
*args: Client commands. | entailment |
def run(self):
"""
Creates new permissions.
"""
from pyoko.lib.utils import get_object_from_path
from zengine.config import settings
model = get_object_from_path(settings.PERMISSION_MODEL)
perm_provider = get_object_from_path(settings.PERMISSION_PROVIDER)
... | Creates new permissions. | entailment |
def run(self):
"""
Creates user, encrypts password.
"""
from zengine.models import User
user = User(username=self.manager.args.username, superuser=self.manager.args.super)
user.set_password(self.manager.args.password)
user.save()
print("New user created wi... | Creates user, encrypts password. | entailment |
def run(self):
"""
Starts a development server for the zengine application
"""
print("Development server started on http://%s:%s. \n\nPress Ctrl+C to stop\n" % (
self.manager.args.addr,
self.manager.args.port)
)
if self.manager.args.server_ty... | Starts a development server for the zengine application | entailment |
def run_with_tornado(self):
"""
runs the tornado/websockets based test server
"""
from zengine.tornado_server.server import runserver
runserver(self.manager.args.addr, int(self.manager.args.port)) | runs the tornado/websockets based test server | entailment |
def run_with_falcon(self):
"""
runs the falcon/http based test server
"""
from wsgiref import simple_server
from zengine.server import app
httpd = simple_server.make_server(self.manager.args.addr, int(self.manager.args.port), app)
httpd.serve_forever() | runs the falcon/http based test server | entailment |
def run(self):
"""
Starts a development server for the zengine application
"""
from zengine.wf_daemon import run_workers, Worker
worker_count = int(self.manager.args.workers or 1)
if not self.manager.args.daemonize:
print("Starting worker(s)")
if wor... | Starts a development server for the zengine application | entailment |
def _prepare_domain(mapping):
"""Prepare a helper dictionary for the domain to temporarily hold some information."""
# Parse the domain-directory mapping
try:
domain, dir = mapping.split(':')
except ValueError:
print("Please provide the sources in the form of '<do... | Prepare a helper dictionary for the domain to temporarily hold some information. | entailment |
def _validate_domains(domains):
"""Check that all domains specified in the settings was provided in the options."""
missing = set(settings.TRANSLATION_DOMAINS.keys()) - set(domains.keys())
if missing:
print('The following domains have been set in the configuration, '
... | Check that all domains specified in the settings was provided in the options. | entailment |
def _extract_translations(self, domains):
"""Extract the translations into `.pot` files"""
for domain, options in domains.items():
# Create the extractor
extractor = babel_frontend.extract_messages()
extractor.initialize_options()
# The temporary location ... | Extract the translations into `.pot` files | entailment |
def _init_update_po_files(self, domains):
"""Update or initialize the `.po` translation files"""
for language in settings.TRANSLATIONS:
for domain, options in domains.items():
if language == options['default']: continue # Default language of the domain doesn't need translati... | Update or initialize the `.po` translation files | entailment |
def _cleanup(self, domains):
"""Remove the temporary '.pot' files that were created for the domains."""
for option in domains.values():
try:
os.remove(option['pot'])
except (IOError, OSError):
# It is not a problem if we can't actually remove the t... | Remove the temporary '.pot' files that were created for the domains. | entailment |
def run(self):
"""
read workflows, checks if it's updated,
tries to update if there aren't any running instances of that wf
"""
from zengine.lib.cache import WFSpecNames
if self.manager.args.clear:
self._clear_models()
return
if self.mana... | read workflows, checks if it's updated,
tries to update if there aren't any running instances of that wf | entailment |
def get_wf_from_path(self, path):
"""
load xml from given path
Args:
path: diagram path
Returns:
"""
with open(path) as fp:
content = fp.read()
return [(os.path.basename(os.path.splitext(path)[0]), content), ] | load xml from given path
Args:
path: diagram path
Returns: | entailment |
def get_workflows(self):
"""
Scans and loads all wf found under WORKFLOW_PACKAGES_PATHS
Yields: XML content of diagram file
"""
for pth in settings.WORKFLOW_PACKAGES_PATHS:
for f in glob.glob("%s/*.bpmn" % pth):
with open(f) as fp:
... | Scans and loads all wf found under WORKFLOW_PACKAGES_PATHS
Yields: XML content of diagram file | entailment |
def check_migration_and_solr(self):
"""
The model or models are checked for migrations that need to be done.
Solr is also checked.
"""
from pyoko.db.schema_update import SchemaUpdater
from socket import error as socket_error
from pyoko.conf import settings... | The model or models are checked for migrations that need to be done.
Solr is also checked. | entailment |
def check_redis():
"""
Redis checks the connection
It displays on the screen whether or not you have a connection.
"""
from pyoko.db.connection import cache
from redis.exceptions import ConnectionError
try:
cache.ping()
print(Check... | Redis checks the connection
It displays on the screen whether or not you have a connection. | entailment |
def check_riak():
"""
Riak checks the connection
It displays on the screen whether or not you have a connection.
"""
from pyoko.db.connection import client
from socket import error as socket_error
try:
if client.ping():
print(_... | Riak checks the connection
It displays on the screen whether or not you have a connection. | entailment |
def check_mq_connection(self):
"""
RabbitMQ checks the connection
It displays on the screen whether or not you have a connection.
"""
import pika
from zengine.client_queue import BLOCKING_MQ_PARAMS
from pika.exceptions import ProbableAuthenticationError, Connectio... | RabbitMQ checks the connection
It displays on the screen whether or not you have a connection. | entailment |
def check_encoding_and_env():
"""
It brings the environment variables to the screen.
The user checks to see if they are using the correct variables.
"""
import sys
import os
if sys.getfilesystemencoding() in ['utf-8', 'UTF-8']:
print(__(u"{0}File syste... | It brings the environment variables to the screen.
The user checks to see if they are using the correct variables. | entailment |
def no_moves(position):
"""
Finds if the game is over.
:type: position: Board
:rtype: bool
"""
return position.no_moves(color.white) \
or position.no_moves(color.black) | Finds if the game is over.
:type: position: Board
:rtype: bool | entailment |
def is_checkmate(position, input_color):
"""
Finds if particular King is checkmated.
:type: position: Board
:type: input_color: Color
:rtype: bool
"""
return position.no_moves(input_color) and \
position.get_king(input_color).in_check(position) | Finds if particular King is checkmated.
:type: position: Board
:type: input_color: Color
:rtype: bool | entailment |
def _paginate(self, current_page, query_set, per_page=10):
"""
Handles pagination of object listings.
Args:
current_page int:
Current page number
query_set (:class:`QuerySet<pyoko:pyoko.db.queryset.QuerySet>`):
Object listing queryset.
per_page int:
... | Handles pagination of object listings.
Args:
current_page int:
Current page number
query_set (:class:`QuerySet<pyoko:pyoko.db.queryset.QuerySet>`):
Object listing queryset.
per_page int:
Objects per page.
Returns:
QuerySet object, pagination ... | entailment |
def create_message(current):
"""
Creates a message for the given channel.
.. code-block:: python
# request:
{
'view':'_zops_create_message',
'message': {
'channel': key, # of channel
'body': string, # message text.,
... | Creates a message for the given channel.
.. code-block:: python
# request:
{
'view':'_zops_create_message',
'message': {
'channel': key, # of channel
'body': string, # message text.,
'type': int, # zengine.messa... | entailment |
def show_channel(current, waited=False):
"""
Initial display of channel content.
Returns channel description, members, no of members, last 20 messages etc.
.. code-block:: python
# request:
{
'view':'_zops_show_channel',
'key': key,
}
... | Initial display of channel content.
Returns channel description, members, no of members, last 20 messages etc.
.. code-block:: python
# request:
{
'view':'_zops_show_channel',
'key': key,
}
# response:
{
'chann... | entailment |
def channel_history(current):
"""
Get old messages for a channel. 20 messages per request
.. code-block:: python
# request:
{
'view':'_zops_channel_history,
'channel_key': key,
'timestamp': datetime, # timestamp data of o... | Get old messages for a channel. 20 messages per request
.. code-block:: python
# request:
{
'view':'_zops_channel_history,
'channel_key': key,
'timestamp': datetime, # timestamp data of oldest shown message
}
... | entailment |
def report_last_seen_message(current):
"""
Push timestamp of latest message of an ACTIVE channel.
This view should be called with timestamp of latest message;
- When user opens (clicks on) a channel.
- Periodically (eg: setInterval for 15secs) while user staying in a channel.
.. code-block:: ... | Push timestamp of latest message of an ACTIVE channel.
This view should be called with timestamp of latest message;
- When user opens (clicks on) a channel.
- Periodically (eg: setInterval for 15secs) while user staying in a channel.
.. code-block:: python
# request:
{
... | entailment |
def list_channels(current):
"""
List channel memberships of current user
.. code-block:: python
# request:
{
'view':'_zops_list_channels',
}
# response:
{
'channels': [
{... | List channel memberships of current user
.. code-block:: python
# request:
{
'view':'_zops_list_channels',
}
# response:
{
'channels': [
{'name': string, # name of channel
... | entailment |
def unread_count(current):
"""
Number of unread messages for current user
.. code-block:: python
# request:
{
'view':'_zops_unread_count',
}
# response:
{
'status': 'OK',
'co... | Number of unread messages for current user
.. code-block:: python
# request:
{
'view':'_zops_unread_count',
}
# response:
{
'status': 'OK',
'code': 200,
'notifications': ... | entailment |
def get_notifications(current):
"""
Returns last N notifications for current user
.. code-block:: python
# request:
{
'view':'_zops_unread_messages',
'amount': int, # Optional, defaults to 8
}
# response:
... | Returns last N notifications for current user
.. code-block:: python
# request:
{
'view':'_zops_unread_messages',
'amount': int, # Optional, defaults to 8
}
# response:
{
'status': 'OK',... | entailment |
def create_channel(current):
"""
Create a public channel. Can be a broadcast channel or normal chat room.
Chat room and broadcast distinction will be made at user subscription phase.
.. code-block:: python
# request:
{
'view':'_zops_create_chan... | Create a public channel. Can be a broadcast channel or normal chat room.
Chat room and broadcast distinction will be made at user subscription phase.
.. code-block:: python
# request:
{
'view':'_zops_create_channel',
'name': string,
... | entailment |
def add_members(current):
"""
Subscribe member(s) to a channel
.. code-block:: python
# request:
{
'view':'_zops_add_members',
'channel_key': key,
'read_only': boolean, # true if this is a Broadcast channel,
... | Subscribe member(s) to a channel
.. code-block:: python
# request:
{
'view':'_zops_add_members',
'channel_key': key,
'read_only': boolean, # true if this is a Broadcast channel,
# false if it's a... | entailment |
def add_unit_to_channel(current):
"""
Subscribe users of a given unit to given channel
JSON API:
.. code-block:: python
# request:
{
'view':'_zops_add_unit_to_channel',
'unit_key': key,
'ch... | Subscribe users of a given unit to given channel
JSON API:
.. code-block:: python
# request:
{
'view':'_zops_add_unit_to_channel',
'unit_key': key,
'channel_key': key,
'read_only': ... | entailment |
def search_user(current):
"""
Search users for adding to a public room
or creating one to one direct messaging
.. code-block:: python
# request:
{
'view':'_zops_search_user',
'query': string,
}
# res... | Search users for adding to a public room
or creating one to one direct messaging
.. code-block:: python
# request:
{
'view':'_zops_search_user',
'query': string,
}
# response:
{
'... | entailment |
def search_unit(current):
"""
Search on units for subscribing it's users to a channel
.. code-block:: python
# request:
{
'view':'_zops_search_unit',
'query': string,
}
# response:
{
... | Search on units for subscribing it's users to a channel
.. code-block:: python
# request:
{
'view':'_zops_search_unit',
'query': string,
}
# response:
{
'results': [('name', 'key'), ],
... | entailment |
def create_direct_channel(current):
"""
Create a One-To-One channel between current and selected user.
.. code-block:: python
# request:
{
'view':'_zops_create_direct_channel',
'user_key': key,
}
# response:
{
'des... | Create a One-To-One channel between current and selected user.
.. code-block:: python
# request:
{
'view':'_zops_create_direct_channel',
'user_key': key,
}
# response:
{
'description': string,
'no_of_members': ... | entailment |
def find_message(current):
"""
Search in messages. If "channel_key" given, search will be limited to that channel,
otherwise search will be performed on all of user's subscribed channels.
.. code-block:: python
# request:
{
'view':'_zops_search_... | Search in messages. If "channel_key" given, search will be limited to that channel,
otherwise search will be performed on all of user's subscribed channels.
.. code-block:: python
# request:
{
'view':'_zops_search_unit,
'channel_key': key,
... | entailment |
def delete_channel(current):
"""
Delete a channel
.. code-block:: python
# request:
{
'view':'_zops_delete_channel,
'channel_key': key,
}
# response:
{
'status': 'OK',
... | Delete a channel
.. code-block:: python
# request:
{
'view':'_zops_delete_channel,
'channel_key': key,
}
# response:
{
'status': 'OK',
'code': 200
} | entailment |
def edit_channel(current):
"""
Update channel name or description
.. code-block:: python
# request:
{
'view':'_zops_edit_channel,
'channel_key': key,
'name': string,
'description': string,
... | Update channel name or description
.. code-block:: python
# request:
{
'view':'_zops_edit_channel,
'channel_key': key,
'name': string,
'description': string,
}
# response:
... | entailment |
def pin_channel(current):
"""
Pin a channel to top of channel list
.. code-block:: python
# request:
{
'view':'_zops_pin_channel,
'channel_key': key,
}
# response:
{
'status':... | Pin a channel to top of channel list
.. code-block:: python
# request:
{
'view':'_zops_pin_channel,
'channel_key': key,
}
# response:
{
'status': 'OK',
'code': 200
... | entailment |
def delete_message(current):
"""
Delete a message
.. code-block:: python
# request:
{
'view':'_zops_delete_message,
'message_key': key,
}
# response:
{
'key': key,
... | Delete a message
.. code-block:: python
# request:
{
'view':'_zops_delete_message,
'message_key': key,
}
# response:
{
'key': key,
'status': 'OK',
'code': ... | entailment |
def edit_message(current):
"""
Edit a message a user own.
.. code-block:: python
# request:
{
'view':'_zops_edit_message',
'message': {
'body': string, # message text
'key': key
}
}
# response:
... | Edit a message a user own.
.. code-block:: python
# request:
{
'view':'_zops_edit_message',
'message': {
'body': string, # message text
'key': key
}
}
# response:
{
'status': string,... | entailment |
def flag_message(current):
"""
Flag inappropriate messages
.. code-block:: python
# request:
{
'view':'_zops_flag_message',
'message_key': key,
}
# response:
{
'
'status': 'Created',
'code': 201,
... | Flag inappropriate messages
.. code-block:: python
# request:
{
'view':'_zops_flag_message',
'message_key': key,
}
# response:
{
'
'status': 'Created',
'code': 201,
} | entailment |
def unflag_message(current):
"""
remove flag of a message
.. code-block:: python
# request:
{
'view':'_zops_flag_message',
'key': key,
}
# response:
{
'
'status': 'OK',
'code': 200,
}
"... | remove flag of a message
.. code-block:: python
# request:
{
'view':'_zops_flag_message',
'key': key,
}
# response:
{
'
'status': 'OK',
'code': 200,
} | entailment |
def get_message_actions(current):
"""
Returns applicable actions for current user for given message key
.. code-block:: python
# request:
{
'view':'_zops_get_message_actions',
'key': key,
}
# response:
{
'actions':[('name_stri... | Returns applicable actions for current user for given message key
.. code-block:: python
# request:
{
'view':'_zops_get_message_actions',
'key': key,
}
# response:
{
'actions':[('name_string', 'cmd_string'),]
'status': str... | entailment |
def add_to_favorites(current):
"""
Favorite a message
.. code-block:: python
# request:
{
'view':'_zops_add_to_favorites,
'key': key,
}
# response:
{
'status': 'Created',
'code': 201
'favorit... | Favorite a message
.. code-block:: python
# request:
{
'view':'_zops_add_to_favorites,
'key': key,
}
# response:
{
'status': 'Created',
'code': 201
'favorite_key': key
} | entailment |
def remove_from_favorites(current):
"""
Remove a message from favorites
.. code-block:: python
# request:
{
'view':'_zops_remove_from_favorites,
'key': key,
}
# response:
{
'status': 'OK',
'code': 200
... | Remove a message from favorites
.. code-block:: python
# request:
{
'view':'_zops_remove_from_favorites,
'key': key,
}
# response:
{
'status': 'OK',
'code': 200
} | entailment |
def list_favorites(current):
"""
List user's favorites. If "channel_key" given, will return favorites belong to that channel.
.. code-block:: python
# request:
{
'view':'_zops_list_favorites,
'channel_key': key,
}
# response:
{... | List user's favorites. If "channel_key" given, will return favorites belong to that channel.
.. code-block:: python
# request:
{
'view':'_zops_list_favorites,
'channel_key': key,
}
# response:
{
'status': 'OK',
... | entailment |
def get_or_create_direct_channel(cls, initiator_key, receiver_key):
"""
Creates a direct messaging channel between two user
Args:
initiator: User, who want's to make first contact
receiver: User, other party
Returns:
(Channel, receiver_name)
... | Creates a direct messaging channel between two user
Args:
initiator: User, who want's to make first contact
receiver: User, other party
Returns:
(Channel, receiver_name) | entailment |
def create_exchange(self):
"""
Creates MQ exchange for this channel
Needs to be defined only once.
"""
mq_channel = self._connect_mq()
mq_channel.exchange_declare(exchange=self.code_name,
exchange_type='fanout',
... | Creates MQ exchange for this channel
Needs to be defined only once. | entailment |
def delete_exchange(self):
"""
Deletes MQ exchange for this channel
Needs to be defined only once.
"""
mq_channel = self._connect_mq()
mq_channel.exchange_delete(exchange=self.code_name) | Deletes MQ exchange for this channel
Needs to be defined only once. | entailment |
def get_channel_listing(self):
"""
serialized form for channel listing
"""
return {'name': self.name,
'key': self.channel.key,
'type': self.channel.typ,
'read_only': self.read_only,
'is_online': self.is_online(),
... | serialized form for channel listing | entailment |
def create_exchange(self):
"""
Creates user's private exchange
Actually user's private channel needed to be defined only once,
and this should be happened when user first created.
But since this has a little performance cost,
to be safe we always call it before binding t... | Creates user's private exchange
Actually user's private channel needed to be defined only once,
and this should be happened when user first created.
But since this has a little performance cost,
to be safe we always call it before binding to the channel we currently subscribe | entailment |
def bind_to_channel(self):
"""
Binds (subscribes) users private exchange to channel exchange
Automatically called at creation of subscription record.
"""
if self.channel.code_name != self.user.prv_exchange:
channel = self._connect_mq()
channel.exchange_bin... | Binds (subscribes) users private exchange to channel exchange
Automatically called at creation of subscription record. | entailment |
def serialize(self, user=None):
"""
Serializes message for given user.
Note:
Should be called before first save(). Otherwise "is_update" will get wrong value.
Args:
user: User object
Returns:
Dict. JSON serialization ready dictionary object
... | Serializes message for given user.
Note:
Should be called before first save(). Otherwise "is_update" will get wrong value.
Args:
user: User object
Returns:
Dict. JSON serialization ready dictionary object | entailment |
def _republish(self):
"""
Re-publishes updated message
"""
mq_channel = self.channel._connect_mq()
mq_channel.basic_publish(exchange=self.channel.key, routing_key='',
body=json.dumps(self.serialize())) | Re-publishes updated message | entailment |
def defaultCrawlId():
"""
Provide a reasonable default crawl name using the user name and date
"""
timestamp = datetime.now().isoformat().replace(':', '_')
user = getuser()
return '_'.join(('crawl', user, timestamp)) | Provide a reasonable default crawl name using the user name and date | entailment |
def main(argv=None):
"""Run Nutch command using REST API."""
global Verbose, Mock
if argv is None:
argv = sys.argv
if len(argv) < 5: die('Bad args')
try:
opts, argv = getopt.getopt(argv[1:], 'hs:p:mv',
['help', 'server=', 'port=', 'mock', 'verbose'])
except getopt.Geto... | Run Nutch command using REST API. | entailment |
def call(self, verb, servicePath, data=None, headers=None, forceText=False, sendJson=True):
"""Call the Nutch Server, do some error checking, and return the response.
:param verb: One of nutch.RequestVerbs
:param servicePath: path component of URL to append to endpoint, e.g. '/config'
:... | Call the Nutch Server, do some error checking, and return the response.
:param verb: One of nutch.RequestVerbs
:param servicePath: path component of URL to append to endpoint, e.g. '/config'
:param data: Data to attach to this request
:param headers: headers to attach to this request, d... | entailment |
def create(self, cid, configData):
"""
Create a new named (cid) configuration from a parameter dictionary (config_data).
"""
configArgs = {'configId': cid, 'params': configData, 'force': True}
cid = self.server.call('post', "/config/create", configArgs, forceText=True, headers=Te... | Create a new named (cid) configuration from a parameter dictionary (config_data). | entailment |
def list(self, allJobs=False):
"""
Return list of jobs at this endpoint.
Call get(allJobs=True) to see all jobs, not just the ones managed by this Client
"""
jobs = self.server.call('get', '/job')
return [Job(job['id'], self.server) for job in jobs if allJobs or self._... | Return list of jobs at this endpoint.
Call get(allJobs=True) to see all jobs, not just the ones managed by this Client | entailment |
def create(self, command, **args):
"""
Create a job given a command
:param command: Nutch command, one of nutch.LegalJobs
:param args: Additional arguments to pass to the job
:return: The created Job
"""
command = command.upper()
if command not in LegalJo... | Create a job given a command
:param command: Nutch command, one of nutch.LegalJobs
:param args: Additional arguments to pass to the job
:return: The created Job | entailment |
def inject(self, seed=None, urlDir=None, **args):
"""
:param seed: A Seed object (this or urlDir must be specified)
:param urlDir: The directory on the server containing the seed list (this or urlDir must be specified)
:param args: Extra arguments for the job
:return: a created J... | :param seed: A Seed object (this or urlDir must be specified)
:param urlDir: The directory on the server containing the seed list (this or urlDir must be specified)
:param args: Extra arguments for the job
:return: a created Job object | entailment |
def create(self, sid, seedList):
"""
Create a new named (sid) Seed from a list of seed URLs
:param sid: the name to assign to the new seed list
:param seedList: the list of seeds to use
:return: the created Seed object
"""
seedUrl = lambda uid, url: {"id": uid, ... | Create a new named (sid) Seed from a list of seed URLs
:param sid: the name to assign to the new seed list
:param seedList: the list of seeds to use
:return: the created Seed object | entailment |
def createFromFile(self, sid, filename):
"""
Create a new named (sid) Seed from a file containing URLs
It's assumed URLs are whitespace seperated.
:param sid: the name to assign to the new seed list
:param filename: the name of the file that contains URLs
:return: the cr... | Create a new named (sid) Seed from a file containing URLs
It's assumed URLs are whitespace seperated.
:param sid: the name to assign to the new seed list
:param filename: the name of the file that contains URLs
:return: the created Seed object | entailment |
def _nextJob(self, job, nextRound=True):
"""
Given a completed job, start the next job in the round, or return None
:param nextRound: whether to start jobs from the next round if the current round is completed.
:return: the newly started Job, or None if no job was started
"""
... | Given a completed job, start the next job in the round, or return None
:param nextRound: whether to start jobs from the next round if the current round is completed.
:return: the newly started Job, or None if no job was started | entailment |
def progress(self, nextRound=True):
"""
Check the status of the current job, activate the next job if it's finished, and return the active job
If the current job has failed, a NutchCrawlException will be raised with no jobs attached.
:param nextRound: whether to start jobs from the nex... | Check the status of the current job, activate the next job if it's finished, and return the active job
If the current job has failed, a NutchCrawlException will be raised with no jobs attached.
:param nextRound: whether to start jobs from the next round if the current job/round is completed.
:... | entailment |
def nextRound(self):
"""
Execute all jobs in the current round and return when they have finished.
If a job fails, a NutchCrawlException will be raised, with all completed jobs from this round attached
to the exception.
:return: a list of all completed Jobs
"""
... | Execute all jobs in the current round and return when they have finished.
If a job fails, a NutchCrawlException will be raised, with all completed jobs from this round attached
to the exception.
:return: a list of all completed Jobs | entailment |
def waitAll(self):
"""
Execute all queued rounds and return when they have finished.
If a job fails, a NutchCrawlException will be raised, with all completed jobs attached
to the exception
:return: a list of jobs completed for each round, organized by round (list-of-lists)
... | Execute all queued rounds and return when they have finished.
If a job fails, a NutchCrawlException will be raised, with all completed jobs attached
to the exception
:return: a list of jobs completed for each round, organized by round (list-of-lists) | entailment |
def Jobs(self, crawlId=None):
"""
Create a JobClient for listing and creating jobs.
The JobClient inherits the confId from the Nutch client.
:param crawlId: crawlIds to use for this client. If not provided, will be generated
by nutch.defaultCrawlId()
:return: a JobClie... | Create a JobClient for listing and creating jobs.
The JobClient inherits the confId from the Nutch client.
:param crawlId: crawlIds to use for this client. If not provided, will be generated
by nutch.defaultCrawlId()
:return: a JobClient | entailment |
def Crawl(self, seed, seedClient=None, jobClient=None, rounds=1, index=True):
"""
Launch a crawl using the given seed
:param seed: Type (Seed or SeedList) - used for crawl
:param seedClient: if a SeedList is given, the SeedClient to upload, if None a default will be created
:para... | Launch a crawl using the given seed
:param seed: Type (Seed or SeedList) - used for crawl
:param seedClient: if a SeedList is given, the SeedClient to upload, if None a default will be created
:param jobClient: the JobClient to be used, if None a default will be created
:param rounds: th... | entailment |
def haproxy(line):
#TODO Handle all message formats
'''
>>> import pprint
>>> input_line1 = 'Apr 24 00:00:02 node haproxy[12298]: 1.1.1.1:48660 [24/Apr/2019:00:00:02.358] pre-staging~ pre-staging_doc/pre-staging_active 261/0/2/8/271 200 2406 - - ---- 4/4/0/1/0 0/0 {AAAAAA:AAAAA_AAAAA:AAAAA_AAAAA_AAAAA:3... | >>> import pprint
>>> input_line1 = 'Apr 24 00:00:02 node haproxy[12298]: 1.1.1.1:48660 [24/Apr/2019:00:00:02.358] pre-staging~ pre-staging_doc/pre-staging_active 261/0/2/8/271 200 2406 - - ---- 4/4/0/1/0 0/0 {AAAAAA:AAAAA_AAAAA:AAAAA_AAAAA_AAAAA:300A||| user@mail.net:sdasdasdasdsdasAHDivsjd=|user@mail.net|2018} "G... | entailment |
def nginx_access(line):
'''
>>> import pprint
>>> input_line1 = '{ \
"remote_addr": "127.0.0.1","remote_user": "-","timestamp": "1515144699.201", \
"request": "GET / HTTP/1.1","status": "200","request_time": "0.000", \
"body_bytes_sent": "396","htt... | >>> import pprint
>>> input_line1 = '{ \
"remote_addr": "127.0.0.1","remote_user": "-","timestamp": "1515144699.201", \
"request": "GET / HTTP/1.1","status": "200","request_time": "0.000", \
"body_bytes_sent": "396","http_referer": "-","http_user_agent": "... | entailment |
def mongodb(line):
'''
>>> import pprint
>>> input_line1 = '2017-08-17T07:56:33.489+0200 I REPL [signalProcessingThread] shutting down replication subsystems'
>>> output_line1 = mongodb(input_line1)
>>> pprint.pprint(output_line1)
{'data': {'component': 'REPL',
'context': '[sig... | >>> import pprint
>>> input_line1 = '2017-08-17T07:56:33.489+0200 I REPL [signalProcessingThread] shutting down replication subsystems'
>>> output_line1 = mongodb(input_line1)
>>> pprint.pprint(output_line1)
{'data': {'component': 'REPL',
'context': '[signalProcessingThread]',
... | entailment |
def django(line):
'''
>>> import pprint
>>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }'
>>> output_line1... | >>> import pprint
>>> input_line1 = '[23/Aug/2017 11:35:25] INFO [app.middleware_log_req:50]View func called:{"exception": null,"processing_time": 0.00011801719665527344, "url": "<url>",host": "localhost", "user": "testing", "post_contents": "", "method": "POST" }'
>>> output_line1 = django(input_line1)
>>>... | entailment |
def basescript(line):
'''
>>> import pprint
>>> input_line = '{"level": "warning", "timestamp": "2018-02-07T06:37:00.297610Z", "event": "exited via keyboard interrupt", "type": "log", "id": "20180207T063700_4d03fe800bd111e89ecb96000007bc65", "_": {"ln": 58, "file": "/usr/local/lib/python2.7/dist-packages/ba... | >>> import pprint
>>> input_line = '{"level": "warning", "timestamp": "2018-02-07T06:37:00.297610Z", "event": "exited via keyboard interrupt", "type": "log", "id": "20180207T063700_4d03fe800bd111e89ecb96000007bc65", "_": {"ln": 58, "file": "/usr/local/lib/python2.7/dist-packages/basescript/basescript.py", "name": "... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.