_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q262800
remove
validation
def remove(group_id, user_id): """Remove user from a group.""" group = Group.query.get_or_404(group_id) user = User.query.get_or_404(user_id) if group.can_edit(current_user): try: group.remove_member(user) except Exception as e: flash(str(e), "error") ...
python
{ "resource": "" }
q262801
accept
validation
def accept(group_id): """Accpet pending invitation.""" membership = Membership.query.get_or_404((current_user.get_id(), group_id)) # no permission check, because they are checked during Memberships creating try: membership.accept() except Exception as e: flash(str(e), 'error') ...
python
{ "resource": "" }
q262802
locate_spheres
validation
def locate_spheres(image, feature_rad, dofilter=False, order=(3 ,3, 3), trim_edge=True, **kwargs): """ Get an initial featuring of sphere positions in an image. Parameters ----------- image : :class:`peri.util.Image` object Image object which defines the image file as we...
python
{ "resource": "" }
q262803
get_initial_featuring
validation
def get_initial_featuring(statemaker, feature_rad, actual_rad=None, im_name=None, tile=None, invert=True, desc='', use_full_path=False, featuring_params={}, statemaker_kwargs={}, **kwargs): """ Completely optimizes a state from an image of roughly monodisperse particles. The user can in...
python
{ "resource": "" }
q262804
feature_from_pos_rad
validation
def feature_from_pos_rad(statemaker, pos, rad, im_name=None, tile=None, desc='', use_full_path=False, statemaker_kwargs={}, **kwargs): """ Gets a completely-optimized state from an image and an initial guess of particle positions and radii. The state is periodically saved during optimization, w...
python
{ "resource": "" }
q262805
optimize_from_initial
validation
def optimize_from_initial(s, max_mem=1e9, invert='guess', desc='', rz_order=3, min_rad=None, max_rad=None): """ Optimizes a state from an initial set of positions and radii, without any known microscope parameters. Parameters ---------- s : :class:`peri.states.ImageState` ...
python
{ "resource": "" }
q262806
get_particles_featuring
validation
def get_particles_featuring(feature_rad, state_name=None, im_name=None, use_full_path=False, actual_rad=None, invert=True, featuring_params={}, **kwargs): """ Combines centroid featuring with the globals from a previous state. Runs trackpy.locate on an image, sets the globals from a previou...
python
{ "resource": "" }
q262807
_pick_state_im_name
validation
def _pick_state_im_name(state_name, im_name, use_full_path=False): """ If state_name or im_name is None, picks them interactively through Tk, and then sets with or without the full path. Parameters ---------- state_name : {string, None} The name of the state. If None, selected t...
python
{ "resource": "" }
q262808
_translate_particles
validation
def _translate_particles(s, max_mem=1e9, desc='', min_rad='calc', max_rad='calc', invert='guess', rz_order=0, do_polish=True): """ Workhorse for translating particles. See get_particles_featuring for docs. """ if desc is not None: desc_trans = desc + 'translate-particles' desc_bu...
python
{ "resource": "" }
q262809
link_zscale
validation
def link_zscale(st): """Links the state ``st`` psf zscale with the global zscale""" # FIXME should be made more generic to other parameters and categories psf = st.get('psf') psf.param_dict['zscale'] = psf.param_dict['psf-zscale'] psf.params[psf.params.index('psf-zscale')] = 'zscale' psf.global_...
python
{ "resource": "" }
q262810
finish_state
validation
def finish_state(st, desc='finish-state', invert='guess'): """ Final optimization for the best-possible state. Runs a local add-subtract to capture any difficult-to-feature particles, then does another set of optimization designed to get to the best possible fit. Parameters ---------- ...
python
{ "resource": "" }
q262811
makestate
validation
def makestate(im, pos, rad, slab=None, mem_level='hi'): """ Workhorse for creating & optimizing states with an initial centroid guess. This is an example function that works for a particular microscope. For your own microscope, you'll need to change particulars such as the psf type and the orde...
python
{ "resource": "" }
q262812
_calc_ilm_order
validation
def _calc_ilm_order(imshape): """ Calculates an ilm order based on the shape of an image. This is based on something that works for our particular images. Your mileage will vary. Parameters ---------- imshape : 3-element list-like The shape of the image. Returns -------...
python
{ "resource": "" }
q262813
ResponseObject._check_for_inception
validation
def _check_for_inception(self, root_dict): ''' Used to check if there is a dict in a dict ''' for key in root_dict: if isinstance(root_dict[key], dict): root_dict[key] = ResponseObject(root_dict[key]) return root_dict
python
{ "resource": "" }
q262814
BarnesStreakLegPoly2P1D.randomize_parameters
validation
def randomize_parameters(self, ptp=0.2, fourier=False, vmin=None, vmax=None): """ Create random parameters for this ILM that mimic experiments as closely as possible without real assumptions. """ if vmin is not None and vmax is not None: ptp = vmax - vmin elif...
python
{ "resource": "" }
q262815
BarnesXYLegPolyZ._barnes
validation
def _barnes(self, pos): """Creates a barnes interpolant & calculates its values""" b_in = self.b_in dist = lambda x: np.sqrt(np.dot(x,x)) #we take a filter size as the max distance between the grids along #x or y: sz = self.npts[1] coeffs = self.get_values(self.ba...
python
{ "resource": "" }
q262816
Profile.schedules
validation
def schedules(self): ''' Returns details of the posting schedules associated with a social media profile. ''' url = PATHS['GET_SCHEDULES'] % self.id self.__schedules = self.api.get(url=url) return self.__schedules
python
{ "resource": "" }
q262817
Profile.schedules
validation
def schedules(self, schedules): ''' Set the posting schedules for the specified social media profile. ''' url = PATHS['UPDATE_SCHEDULES'] % self.id data_format = "schedules[0][%s][]=%s&" post_data = "" for format_type, values in schedules.iteritems(): for value in values: ...
python
{ "resource": "" }
q262818
moment
validation
def moment(p, v, order=1): """ Calculates the moments of the probability distribution p with vector v """ if order == 1: return (v*p).sum() elif order == 2: return np.sqrt( ((v**2)*p).sum() - (v*p).sum()**2 )
python
{ "resource": "" }
q262819
ExactPSF.psf_slice
validation
def psf_slice(self, zint, size=11, zoffset=0., getextent=False): """ Calculates the 3D psf at a particular z pixel height Parameters ---------- zint : float z pixel height in image coordinates , converted to 1/k by the function using the slab position as ...
python
{ "resource": "" }
q262820
ExactPSF._tz
validation
def _tz(self, z): """ Transform z to real-space coordinates from tile coordinates """ return (z-self.param_dict['psf-zslab'])*self.param_dict[self.zscale]
python
{ "resource": "" }
q262821
ExactPSF._kpad
validation
def _kpad(self, field, finalshape, zpad=False, norm=True): """ fftshift and pad the field with zeros until it has size finalshape. if zpad is off, then no padding is put on the z direction. returns the fourier transform of the field """ currshape = np.array(field.shape) ...
python
{ "resource": "" }
q262822
ExactLineScanConfocalPSF.pack_args
validation
def pack_args(self): """ Pack the parameters into the form necessary for the integration routines above. For example, packs for calculate_linescan_psf """ mapper = { 'psf-kfki': 'kfki', 'psf-alpha': 'alpha', 'psf-n2n1': 'n2n1', 'ps...
python
{ "resource": "" }
q262823
ExactLineScanConfocalPSF.psffunc
validation
def psffunc(self, *args, **kwargs): """Calculates a linescan psf""" if self.polychromatic: func = psfcalc.calculate_polychrome_linescan_psf else: func = psfcalc.calculate_linescan_psf return func(*args, **kwargs)
python
{ "resource": "" }
q262824
ExactPinholeConfocalPSF.psffunc
validation
def psffunc(self, x, y, z, **kwargs): """Calculates a pinhole psf""" #do_pinhole?? FIXME if self.polychromatic: func = psfcalc.calculate_polychrome_pinhole_psf else: func = psfcalc.calculate_pinhole_psf x0, y0 = [psfcalc.vec_to_halfvec(v) for v in [x,y]] ...
python
{ "resource": "" }
q262825
BetsApi._req
validation
def _req(self, url, method='GET', **kw): '''Make request and convert JSON response to python objects''' send = requests.post if method == 'POST' else requests.get try: r = send( url, headers=self._token_header(), timeout=self.settings['...
python
{ "resource": "" }
q262826
BetsApi.get_active_bets
validation
def get_active_bets(self, project_id=None): '''Returns all active bets''' url = urljoin( self.settings['bets_url'], 'bets?state=fresh,active,accept_end&page=1&page_size=100') if project_id is not None: url += '&kava_project_id={}'.format(project_id) ...
python
{ "resource": "" }
q262827
BetsApi.get_bets
validation
def get_bets(self, type=None, order_by=None, state=None, project_id=None, page=None, page_size=None): """Return bets with given filters and ordering. :param type: return bets only with this type. Use None to include all (default). :param order_by: '-last_st...
python
{ "resource": "" }
q262828
BetsApi.get_project_slug
validation
def get_project_slug(self, bet): '''Return slug of a project that given bet is associated with or None if bet is not associated with any project. ''' if bet.get('form_params'): params = json.loads(bet['form_params']) return params.get('project') return Non...
python
{ "resource": "" }
q262829
BetsApi.subscribe
validation
def subscribe(self, event, bet_ids): '''Subscribe to event for given bet ids.''' if not self._subscriptions.get(event): self._subscriptions[event] = set() self._subscriptions[event] = self._subscriptions[event].union(bet_ids)
python
{ "resource": "" }
q262830
preview
validation
def preview(context): """Opens local preview of your blog website""" config = context.obj pelican(config, '--verbose', '--ignore-cache') server_proc = None os.chdir(config['OUTPUT_DIR']) try: try: command = 'python -m http.server ' + str(PORT) server_proc = run...
python
{ "resource": "" }
q262831
APIConnected.get_collection_endpoint
validation
def get_collection_endpoint(cls): """ Get the relative path to the API resource collection If self.collection_endpoint is not set, it will default to the lowercase name of the resource class plus an "s" and the terminating "/" :param cls: Resource class :return: Relative path to...
python
{ "resource": "" }
q262832
write
validation
def write(context): """Starts a new article""" config = context.obj title = click.prompt('Title') author = click.prompt('Author', default=config.get('DEFAULT_AUTHOR')) slug = slugify(title) creation_date = datetime.now() basename = '{:%Y-%m-%d}_{}.md'.format(creation_date, slug) meta ...
python
{ "resource": "" }
q262833
lint
validation
def lint(context): """Looks for errors in source code of your blog""" config = context.obj try: run('flake8 {dir} --exclude={exclude}'.format( dir=config['CWD'], exclude=','.join(EXCLUDE), )) except SubprocessError: context.exit(1)
python
{ "resource": "" }
q262834
ResourceField.set_real_value_class
validation
def set_real_value_class(self): """ value_class is initially a string with the import path to the resource class, but we need to get the actual class before doing any work We do not expect the actual clas to be in value_class since the beginning to avoid nasty import egg-before-chicken errors ...
python
{ "resource": "" }
q262835
publish
validation
def publish(context): """Saves changes and sends them to GitHub""" header('Recording changes...') run('git add -A') header('Displaying changes...') run('git -c color.status=always status') if not click.confirm('\nContinue publishing'): run('git reset HEAD --') abort(context) ...
python
{ "resource": "" }
q262836
deploy
validation
def deploy(context): """Uploads new version of the blog website""" config = context.obj header('Generating HTML...') pelican(config, '--verbose', production=True) header('Removing unnecessary output...') unnecessary_paths = [ 'author', 'category', 'tag', 'feeds', 'tags.html', ...
python
{ "resource": "" }
q262837
signed_number
validation
def signed_number(number, precision=2): """ Return the given number as a string with a sign in front of it, ie. `+` if the number is positive, `-` otherwise. """ prefix = '' if number <= 0 else '+' number_str = '{}{:.{precision}f}'.format(prefix, number, precision=precision) return number_str
python
{ "resource": "" }
q262838
balance
validation
def balance(ctx): """ Show Zebra balance. Like the hours balance, vacation left, etc. """ backend = plugins_registry.get_backends_by_class(ZebraBackend)[0] timesheet_collection = get_timesheet_collection_for_context(ctx, None) hours_to_be_pushed = timesheet_collection.get_hours(pushed=Fals...
python
{ "resource": "" }
q262839
show_response_messages
validation
def show_response_messages(response_json): """ Show all messages in the `messages` key of the given dict. """ message_type_kwargs = { 'warning': {'fg': 'yellow'}, 'error': {'fg': 'red'}, } for message in response_json.get('messages', []): click.secho(message['text'], **me...
python
{ "resource": "" }
q262840
photos
validation
def photos(context, path): """Adds images to the last article""" config = context.obj header('Looking for the latest article...') article_filename = find_last_article(config['CONTENT_DIR']) if not article_filename: return click.secho('No articles.', fg='red') click.echo(os.path.basenam...
python
{ "resource": "" }
q262841
HashRing._generate_circle
validation
def _generate_circle(self): """Generates the circle. """ total_weight = 0 for node in self.nodes: total_weight += self.weights.get(node, 1) for node in self.nodes: weight = 1 if node in self.weights: weight = self.weights.get(...
python
{ "resource": "" }
q262842
HashRing.get_node
validation
def get_node(self, string_key): """Given a string key a corresponding node in the hash ring is returned. If the hash ring is empty, `None` is returned. """ pos = self.get_node_pos(string_key) if pos is None: return None return self.ring[self._sorted_keys[pos]...
python
{ "resource": "" }
q262843
HashRing.gen_key
validation
def gen_key(self, key): """Given a string key it returns a long value, this long value represents a place on the hash ring. md5 is currently used because it mixes well. """ b_key = self._hash_digest(key) return self._hash_val(b_key, lambda x: x)
python
{ "resource": "" }
q262844
_get_networking_mode
validation
def _get_networking_mode(app): """ Get the Marathon networking mode for the app. """ # Marathon 1.5+: there is a `networks` field networks = app.get('networks') if networks: # Modes cannot be mixed, so assigning the last mode is fine return networks[-1].get('mode', 'container') ...
python
{ "resource": "" }
q262845
_get_container_port_mappings
validation
def _get_container_port_mappings(app): """ Get the ``portMappings`` field for the app container. """ container = app['container'] # Marathon 1.5+: container.portMappings field port_mappings = container.get('portMappings') # Older Marathon: container.docker.portMappings field if port_ma...
python
{ "resource": "" }
q262846
sort_pem_objects
validation
def sort_pem_objects(pem_objects): """ Given a list of pem objects, sort the objects into the private key, leaf certificate, and list of CA certificates in the trust chain. This function assumes that the list of pem objects will contain exactly one private key and exactly one leaf certificate and th...
python
{ "resource": "" }
q262847
raise_for_not_ok_status
validation
def raise_for_not_ok_status(response): """ Raises a `requests.exceptions.HTTPError` if the response has a non-200 status code. """ if response.code != OK: raise HTTPError('Non-200 response code (%s) for url: %s' % ( response.code, uridecode(response.request.absoluteURI))) re...
python
{ "resource": "" }
q262848
_sse_content_with_protocol
validation
def _sse_content_with_protocol(response, handler, **sse_kwargs): """ Sometimes we need the protocol object so that we can manipulate the underlying transport in tests. """ protocol = SseProtocol(handler, **sse_kwargs) finished = protocol.when_finished() response.deliverBody(protocol) r...
python
{ "resource": "" }
q262849
sse_content
validation
def sse_content(response, handler, **sse_kwargs): """ Callback to collect the Server-Sent Events content of a response. Callbacks passed will receive event data. :param response: The response from the SSE request. :param handler: The handler for the SSE protocol. """ # An SS...
python
{ "resource": "" }
q262850
MarathonClient._request
validation
def _request(self, failure, endpoints, *args, **kwargs): """ Recursively make requests to each endpoint in ``endpoints``. """ # We've run out of endpoints, fail if not endpoints: return failure endpoint = endpoints.pop(0) d = super(MarathonClient, sel...
python
{ "resource": "" }
q262851
MarathonClient.get_json_field
validation
def get_json_field(self, field, **kwargs): """ Perform a GET request and get the contents of the JSON response. Marathon's JSON responses tend to contain an object with a single key which points to the actual data of the response. For example /v2/apps returns something like {"ap...
python
{ "resource": "" }
q262852
MarathonClient._get_json_field
validation
def _get_json_field(self, response_json, field_name): """ Get a JSON field from the response JSON. :param: response_json: The parsed JSON content of the response. :param: field_name: The name of the field in the JSON to get. """ if field_name not ...
python
{ "resource": "" }
q262853
Config.parse
validation
def parse( self, value: str, type_: typing.Type[typing.Any] = str, subtype: typing.Type[typing.Any] = str, ) -> typing.Any: """ Parse value from string. Convert :code:`value` to .. code-block:: python >>> parser = Config() >>> ...
python
{ "resource": "" }
q262854
Config.get
validation
def get( self, key: str, default: typing.Any = UNSET, type_: typing.Type[typing.Any] = str, subtype: typing.Type[typing.Any] = str, mapper: typing.Optional[typing.Callable[[object], object]] = None, ) -> typing.Any: """ Parse a value from an environmen...
python
{ "resource": "" }
q262855
MarathonLbClient._request
validation
def _request(self, endpoint, *args, **kwargs): """ Perform a request to a specific endpoint. Raise an error if the status code indicates a client or server error. """ kwargs['url'] = endpoint return (super(MarathonLbClient, self).request(*args, **kwargs) ....
python
{ "resource": "" }
q262856
MarathonLbClient._check_request_results
validation
def _check_request_results(self, results): """ Check the result of each request that we made. If a failure occurred, but some requests succeeded, log and count the failures. If all requests failed, raise an error. :return: The list of responses, with a None value for...
python
{ "resource": "" }
q262857
maybe_key
validation
def maybe_key(pem_path): """ Set up a client key if one does not exist already. https://gist.github.com/glyph/27867a478bb71d8b6046fbfb176e1a33#file-local-certs-py-L32-L50 :type pem_path: twisted.python.filepath.FilePath :param pem_path: The path to the certificate directory to use. :rt...
python
{ "resource": "" }
q262858
maybe_key_vault
validation
def maybe_key_vault(client, mount_path): """ Set up a client key in Vault if one does not exist already. :param client: The Vault API client to use. :param mount_path: The Vault key/value mount path to use. :rtype: twisted.internet.defer.Deferred """ d = client.read_kv2('cli...
python
{ "resource": "" }
q262859
VaultClient.read
validation
def read(self, path, **params): """ Read data from Vault. Returns the JSON-decoded response. """ d = self.request('GET', '/v1/' + path, params=params) return d.addCallback(self._handle_response)
python
{ "resource": "" }
q262860
VaultClient.write
validation
def write(self, path, **data): """ Write data to Vault. Returns the JSON-decoded response. """ d = self.request('PUT', '/v1/' + path, json=data) return d.addCallback(self._handle_response, check_cas=True)
python
{ "resource": "" }
q262861
get_single_header
validation
def get_single_header(headers, key): """ Get a single value for the given key out of the given set of headers. :param twisted.web.http_headers.Headers headers: The set of headers in which to look for the header value :param str key: The header key """ raw_headers = headers.getRa...
python
{ "resource": "" }
q262862
HTTPClient.request
validation
def request(self, method, url=None, **kwargs): """ Perform a request. :param: method: The HTTP method to use (example is `GET`). :param: url: The URL to use. The default value is the URL this client was created with (`self.url`) (example is `http://lo...
python
{ "resource": "" }
q262863
MarathonAcmeServer.listen
validation
def listen(self, reactor, endpoint_description): """ Run the server, i.e. start listening for requests on the given host and port. :param reactor: The ``IReactorTCP`` to use. :param endpoint_description: The Twisted description for the endpoint to listen on. ...
python
{ "resource": "" }
q262864
create_marathon_acme
validation
def create_marathon_acme( client_creator, cert_store, acme_email, allow_multiple_certs, marathon_addrs, marathon_timeout, sse_timeout, mlb_addrs, group, reactor): """ Create a marathon-acme instance. :param client_creator: The txacme client creator function. :param cert_store: ...
python
{ "resource": "" }
q262865
init_storage_dir
validation
def init_storage_dir(storage_dir): """ Initialise the storage directory with the certificates directory and a default wildcard self-signed certificate for HAProxy. :return: the storage path and certs path """ storage_path = FilePath(storage_dir) # Create the default wildcard certificate if...
python
{ "resource": "" }
q262866
init_logging
validation
def init_logging(log_level): """ Initialise the logging by adding an observer to the global log publisher. :param str log_level: The minimum log level to log messages for. """ log_level_filter = LogLevelFilterPredicate( LogLevel.levelWithName(log_level)) log_level_filter.setLogLevelForN...
python
{ "resource": "" }
q262867
_parse_field_value
validation
def _parse_field_value(line): """ Parse the field and value from a line. """ if line.startswith(':'): # Ignore the line return None, None if ':' not in line: # Treat the entire line as the field, use empty string as value return line, '' # Else field is before the ':' a...
python
{ "resource": "" }
q262868
SseProtocol.dataReceived
validation
def dataReceived(self, data): """ Translates bytes into lines, and calls lineReceived. Copied from ``twisted.protocols.basic.LineOnlyReceiver`` but using str.splitlines() to split on ``\r\n``, ``\n``, and ``\r``. """ self.resetTimeout() lines = (self._buffer + da...
python
{ "resource": "" }
q262869
SseProtocol._handle_field_value
validation
def _handle_field_value(self, field, value): """ Handle the field, value pair. """ if field == 'event': self._event = value elif field == 'data': self._data_lines.append(value) elif field == 'id': # Not implemented pass elif field =...
python
{ "resource": "" }
q262870
SseProtocol._dispatch_event
validation
def _dispatch_event(self): """ Dispatch the event to the handler. """ data = self._prepare_data() if data is not None: self._handler(self._event, data) self._reset_event_data()
python
{ "resource": "" }
q262871
MarathonAcme.listen_events
validation
def listen_events(self, reconnects=0): """ Start listening for events from Marathon, running a sync when we first successfully subscribe and triggering a sync on API request events. """ self.log.info('Listening for events from Marathon...') self._attached = False ...
python
{ "resource": "" }
q262872
MarathonAcme.sync
validation
def sync(self): """ Fetch the list of apps from Marathon, find the domains that require certificates, and issue certificates for any domains that don't already have a certificate. """ self.log.info('Starting a sync...') def log_success(result): self.l...
python
{ "resource": "" }
q262873
MarathonAcme._issue_cert
validation
def _issue_cert(self, domain): """ Issue a certificate for the given domain. """ def errback(failure): # Don't fail on some of the errors we could get from the ACME # server, rather just log an error so that we can continue with # other domains. ...
python
{ "resource": "" }
q262874
rm_fwd_refs
validation
def rm_fwd_refs(obj): """When removing an object, other objects with references to the current object should remove those references. This function identifies objects with forward references to the current object, then removes those references. :param obj: Object to which forward references should ...
python
{ "resource": "" }
q262875
rm_back_refs
validation
def rm_back_refs(obj): """When removing an object with foreign fields, back-references from other objects to the current object should be deleted. This function identifies foreign fields of the specified object whose values are not None and which specify back-reference keys, then removes back-references...
python
{ "resource": "" }
q262876
ensure_backrefs
validation
def ensure_backrefs(obj, fields=None): """Ensure that all forward references on the provided object have the appropriate backreferences. :param StoredObject obj: Database record :param list fields: Optional list of field names to check """ for ref in _collect_refs(obj, fields): updated...
python
{ "resource": "" }
q262877
PickleStorage._remove_by_pk
validation
def _remove_by_pk(self, key, flush=True): """Retrieve value from store. :param key: Key """ try: del self.store[key] except Exception as error: pass if flush: self.flush()
python
{ "resource": "" }
q262878
Bot.start
validation
def start(self): """Initializes the bot, plugins, and everything.""" self.bot_start_time = datetime.now() self.webserver = Webserver(self.config['webserver']['host'], self.config['webserver']['port']) self.plugins.load() self.plugins.load_state() self._find_event_handlers...
python
{ "resource": "" }
q262879
Bot.run
validation
def run(self, start=True): """ Connects to slack and enters the main loop. * start - If True, rtm.start API is used. Else rtm.connect API is used For more info, refer to https://python-slackclient.readthedocs.io/en/latest/real_time_messaging.html#rtm-start-vs-rtm-connect ...
python
{ "resource": "" }
q262880
Bot.stop
validation
def stop(self): """Does cleanup of bot and plugins.""" if self.webserver is not None: self.webserver.stop() if not self.test_mode: self.plugins.save_state()
python
{ "resource": "" }
q262881
Bot.send_message
validation
def send_message(self, channel, text, thread=None, reply_broadcast=None): """ Sends a message to the specified channel * channel - The channel to send to. This can be a SlackChannel object, a channel id, or a channel name (without the #) * text - String to send * thread...
python
{ "resource": "" }
q262882
Bot.send_im
validation
def send_im(self, user, text): """ Sends a message to a user as an IM * user - The user to send to. This can be a SlackUser object, a user id, or the username (without the @) * text - String to send """ if isinstance(user, SlackUser): user = user.id ...
python
{ "resource": "" }
q262883
MessageDispatcher.push
validation
def push(self, message): """ Takes a SlackEvent, parses it for a command, and runs against registered plugin """ if self._ignore_event(message): return None, None args = self._parse_message(message) self.log.debug("Searching for command using chunks: %s", args...
python
{ "resource": "" }
q262884
MessageDispatcher._ignore_event
validation
def _ignore_event(self, message): """ message_replied event is not truly a message event and does not have a message.text don't process such events commands may not be idempotent, so ignore message_changed events. """ if hasattr(message, 'subtype') and message.subtype in...
python
{ "resource": "" }
q262885
AuthManager.acl_show
validation
def acl_show(self, msg, args): """Show current allow and deny blocks for the given acl.""" name = args[0] if len(args) > 0 else None if name is None: return "%s: The following ACLs are defined: %s" % (msg.user, ', '.join(self._acl.keys())) if name not in self._acl: ...
python
{ "resource": "" }
q262886
AuthManager.add_user_to_allow
validation
def add_user_to_allow(self, name, user): """Add a user to the given acl allow block.""" # Clear user from both allow and deny before adding if not self.remove_user_from_acl(name, user): return False if name not in self._acl: return False self._acl[name]...
python
{ "resource": "" }
q262887
AuthManager.create_acl
validation
def create_acl(self, name): """Create a new acl.""" if name in self._acl: return False self._acl[name] = { 'allow': [], 'deny': [] } return True
python
{ "resource": "" }
q262888
AuthManager.delete_acl
validation
def delete_acl(self, name): """Delete an acl.""" if name not in self._acl: return False del self._acl[name] return True
python
{ "resource": "" }
q262889
mongo
validation
def mongo(daemon=False, port=20771): '''Run the mongod process. ''' cmd = "mongod --port {0}".format(port) if daemon: cmd += " --fork" run(cmd)
python
{ "resource": "" }
q262890
proxy_factory
validation
def proxy_factory(BaseSchema, label, ProxiedClass, get_key): """Create a proxy to a class instance stored in ``proxies``. :param class BaseSchema: Base schema (e.g. ``StoredObject``) :param str label: Name of class variable to set :param class ProxiedClass: Class to get or create :param function ge...
python
{ "resource": "" }
q262891
with_proxies
validation
def with_proxies(proxy_map, get_key): """Class decorator factory; adds proxy class variables to target class. :param dict proxy_map: Mapping between class variable labels and proxied classes :param function get_key: Extension-specific key function; may return e.g. the current Flask request ...
python
{ "resource": "" }
q262892
ForeignField._to_primary_key
validation
def _to_primary_key(self, value): """ Return primary key; if value is StoredObject, verify that it is loaded. """ if value is None: return None if isinstance(value, self.base_class): if not value._is_loaded: raise exceptions.Databa...
python
{ "resource": "" }
q262893
set_nested
validation
def set_nested(data, value, *keys): """Assign to a nested dictionary. :param dict data: Dictionary to mutate :param value: Value to set :param list *keys: List of nested keys >>> data = {} >>> set_nested(data, 'hi', 'k0', 'k1', 'k2') >>> data {'k0': {'k1': {'k2': 'hi'}}} """ i...
python
{ "resource": "" }
q262894
UserManager.get_by_username
validation
def get_by_username(self, username): """Retrieve user by username""" res = filter(lambda x: x.username == username, self.users.values()) if len(res) > 0: return res[0] return None
python
{ "resource": "" }
q262895
UserManager.set
validation
def set(self, user): """ Adds a user object to the user manager user - a SlackUser object """ self.log.info("Loading user information for %s/%s", user.id, user.username) self.load_user_info(user) self.log.info("Loading user rights for %s/%s", user.id, user.usern...
python
{ "resource": "" }
q262896
UserManager.load_user_rights
validation
def load_user_rights(self, user): """Sets permissions on user object""" if user.username in self.admins: user.is_admin = True elif not hasattr(user, 'is_admin'): user.is_admin = False
python
{ "resource": "" }
q262897
BasePlugin.send_message
validation
def send_message(self, channel, text): """ Used to send a message to the specified channel. * channel - can be a channel or user * text - message to send """ if isinstance(channel, SlackIM) or isinstance(channel, SlackUser): self._bot.send_im(channel, text) ...
python
{ "resource": "" }
q262898
BasePlugin.start_timer
validation
def start_timer(self, duration, func, *args): """ Schedules a function to be called after some period of time. * duration - time in seconds to wait before firing * func - function to be called * args - arguments to pass to the function """ t = threading.Timer(dur...
python
{ "resource": "" }
q262899
BasePlugin.stop_timer
validation
def stop_timer(self, func): """ Stops a timer if it hasn't fired yet * func - the function passed in start_timer """ if func in self._timer_callbacks: t = self._timer_callbacks[func] t.cancel() del self._timer_callbacks[func]
python
{ "resource": "" }