_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q45900
ftr_get_config
train
def ftr_get_config(website_url, exact_host_match=False): """ Download the Five Filters config from centralized repositories. Repositories can be local if you need to override siteconfigs. The first entry found is returned. If no configuration is found, `None` is returned. If :mod:`cacheops` is install...
python
{ "resource": "" }
q45901
SiteConfig.load
train
def load(self, host, exact_host_match=False): """ Load a config for a hostname or url. This method calls :func:`ftr_get_config` and :meth`append` internally. Refer to their docs for details on parameters. """ # Can raise a SiteConfigNotFound, intentionally bubbled. conf...
python
{ "resource": "" }
q45902
SiteConfig.append
train
def append(self, newconfig): """ Append another site config to current instance. All ``newconfig`` attributes are appended one by one to ours. Order matters, eg. current instance values will come first when merging. Thus, if you plan to use some sort of global site config with ...
python
{ "resource": "" }
q45903
write_moc_json
train
def write_moc_json(moc, filename=None, file=None): """Write a MOC in JSON encoding. Either a filename, or an open file object can be specified. """ moc.normalize() obj = {} for (order, cells) in moc: obj['{0}'.format(order)] = sorted(cells) if file is not None: _write_js...
python
{ "resource": "" }
q45904
read_moc_json
train
def read_moc_json(moc, filename=None, file=None): """Read JSON encoded data into a MOC. Either a filename, or an open file object can be specified. """ if file is not None: obj = _read_json(file) else: with open(filename, 'rb') as f: obj = _read_json(f) for (order,...
python
{ "resource": "" }
q45905
CustomFieldsMixin.get_queryset
train
def get_queryset(self): """ For reducing the query count the queryset is expanded with `prefetch_related` and `select_related` depending on the specified fields and nested fields """ self.queryset = super(CustomFieldsMixin, self).get_queryset() serializer_class = self.get...
python
{ "resource": "" }
q45906
Table.read
train
async def read(self, *_id): """Read data from database table. Accepts ids of entries. Returns list of results if success or string with error code and explanation. read(*id) => [(result), (result)] (if success) read(*id) => [] (if missed) read() => {"error":400, "reason":"Missed required fields"} """ ...
python
{ "resource": "" }
q45907
Table.insert
train
async def insert(self, **kwargs): """ Accepts request object, retrieves data from the one`s body and creates new account. """ if kwargs: # Create autoincrement for account pk = await self.autoincrement() kwargs.update({"id": pk}) # Create account with received data and autoincrement await ...
python
{ "resource": "" }
q45908
Table.find
train
async def find(self, **kwargs): """Find all entries with given search key. Accepts named parameter key and arbitrary values. Returns list of entry id`s. find(**kwargs) => document (if exist) find(**kwargs) => {"error":404,"reason":"Not found"} (if does not exist) find() => {"error":400, "reason":"Missed re...
python
{ "resource": "" }
q45909
Table.update
train
async def update(self, _id=None, **new_data): """Updates fields values. Accepts id of sigle entry and fields with values. update(id, **kwargs) => {"success":200, "reason":"Updated"} (if success) update(id, **kwargs) => {"error":400, "reason":"Missed required fields"} (if error) """ if not _id or not ne...
python
{ "resource": "" }
q45910
HTTPEquivRefreshTags.extract
train
def extract(self, html): "Extract http-equiv refresh url to follow." extracted = {} soup = BeautifulSoup(html, parser) for meta_tag in soup.find_all('meta'): if self.key_attr in meta_tag.attrs and 'content' in meta_tag.attrs and \ meta_tag[self.key_attr].lower...
python
{ "resource": "" }
q45911
SignedHTTPClient.request
train
def request(self, *args, **kwargs): """Overrided method. Returns jsonrpc response or fetches exception? returns appropriate data to client and response mail to administrator. """ try: import settings with open(os.path.join(settings.BASE_DIR, "keys.json")) as f: keys = json.load(f) privkey = key...
python
{ "resource": "" }
q45912
ManagementSystemHandler.verify
train
def verify(self): """Abstract method. Signature verifying logic. """ logging.debug("\n\n") logging.debug("[+] -- Verify debugging") logging.debug("\n\n") if self.request.body: logging.debug("\n Request body") logging.debug(self.request.body) data = json.loads(self.request.body) message = jso...
python
{ "resource": "" }
q45913
cli_frontend
train
def cli_frontend(ctx, verbose): """ Boussole is a commandline interface to build Sass projects using libsass. Every project will need a settings file containing all needed settings to build it. """ printout = True if verbose == 0: verbose = 1 printout = False # Verbosit...
python
{ "resource": "" }
q45914
ProjectBase.get_backend_engine
train
def get_backend_engine(self, name, **kwargs): """ Get backend engine from given name. Args: (string): Path to validate. Raises: boussole.exceptions.SettingsBackendError: If given backend name does not match any available engine. Returns:...
python
{ "resource": "" }
q45915
ProjectStarter.commit
train
def commit(self, sourcedir, targetdir, abs_config, abs_sourcedir, abs_targetdir): """ Commit project structure and configuration file Args: sourcedir (string): Source directory path. targetdir (string): Compiled files target directory path. abs...
python
{ "resource": "" }
q45916
ProjectStarter.init
train
def init(self, basedir, config, sourcedir, targetdir, cwd='', commit=True): """ Init project structure and configuration from given arguments Args: basedir (string): Project base directory used to prepend relative paths. If empty or equal to '.', it will be filled wi...
python
{ "resource": "" }
q45917
Grid.get_web_drivers
train
def get_web_drivers(cls, conf, global_capabilities=None): """Prepare 1 selenium driver instance per request browsers :param conf: :param global_capabilities: :return: """ web_drivers = [] if not global_capabilities: global_capabilities = {} el...
python
{ "resource": "" }
q45918
move_if_not_on_dow
train
def move_if_not_on_dow(original, replacement, dow_not_orig, dow_replacement): """ Return a lambda function. Lambda checks that either the original day does not fall on a given weekday, or that the replacement day does fall on the expected weekday. """ return lambda x: ( (x.hdate.day == ...
python
{ "resource": "" }
q45919
plot_moc
train
def plot_moc(moc, order=None, antialias=0, filename=None, projection='cart', color='blue', title='', coord_sys='C', graticule=True, **kwargs): """Plot a MOC using Healpy. This generates a plot of the MOC at the specified order, or the MOC's current order if this is not specified. ...
python
{ "resource": "" }
q45920
HistoryHandler.post
train
def post(self): """Accepts jsorpc post request. Retrieves data from request body. """ # type(data) = dict data = json.loads(self.request.body.decode()) # type(method) = str method = data["method"] # type(params) = dict params = data["params"] ...
python
{ "resource": "" }
q45921
make_server
train
def make_server(function, port, authkey, qsize=None): """Create a manager containing input and output queues, and a function to map inputs over. A connecting client can read the stored function, apply it to items in the input queue and post back to the output queue :param function: function to appl...
python
{ "resource": "" }
q45922
make_client
train
def make_client(ip, port, authkey): """Create a manager to connect to our server manager :param ip: ip address of server :param port: port over which to server :param authkey: authorization key """ QueueManager.register('get_job_q') QueueManager.register('get_result_q') QueueManager.re...
python
{ "resource": "" }
q45923
compile_command
train
def compile_command(context, backend, config): """ Compile Sass project sources to CSS """ logger = logging.getLogger("boussole") logger.info(u"Building project") # Discover settings file try: discovering = Discover(backends=[SettingsBackendJson, ...
python
{ "resource": "" }
q45924
Vendapin._checksum
train
def _checksum(self, packet): '''calculate the XOR checksum of a packet in string format''' xorsum = 0 for s in packet: xorsum ^= ord(s) return xorsum
python
{ "resource": "" }
q45925
Vendapin.was_packet_accepted
train
def was_packet_accepted(self, packet): '''parse the "command" byte from the response packet to get a "response code"''' self._validatepacket(packet) cmd = ord(packet[2]) if cmd == Vendapin.ACK: # Accepted/Positive Status return True elif cmd == Vendapin.NAK: # Rejecte...
python
{ "resource": "" }
q45926
Vendapin.parsedata
train
def parsedata(self, packet): '''parse the data section of a packet, it can range from 0 to many bytes''' data = [] datalength = ord(packet[3]) position = 4 while position < datalength + 4: data.append(packet[position]) position += 1 return data
python
{ "resource": "" }
q45927
Vendapin.sendcommand
train
def sendcommand(self, command, datalength=0, data=None): '''send a packet in the vendapin format''' packet = chr(Vendapin.STX) + chr(Vendapin.ADD) + chr(command) + chr(datalength) if datalength > 0: packet += chr(data) packet += chr(Vendapin.ETX) sendpacket = packet +...
python
{ "resource": "" }
q45928
Vendapin.request_status
train
def request_status(self): '''request the status of the card dispenser and return the status code''' self.sendcommand(Vendapin.REQUEST_STATUS) # wait for the reply time.sleep(1) response = self.receivepacket() if self.was_packet_accepted(response): return Venda...
python
{ "resource": "" }
q45929
Vendapin.dispense
train
def dispense(self): '''dispense a card if ready, otherwise throw an Exception''' self.sendcommand(Vendapin.DISPENSE) # wait for the reply time.sleep(1) # parse the reply response = self.receivepacket() print('Vendapin.dispense(): ' + str(response)) if not ...
python
{ "resource": "" }
q45930
Vendapin.reset
train
def reset(self, hard=False): '''reset the card dispense, either soft or hard based on boolean 2nd arg''' if hard: self.sendcommand(Vendapin.RESET, 1, 0x01) time.sleep(2) else: self.sendcommand(Vendapin.RESET) time.sleep(2) # parse the r...
python
{ "resource": "" }
q45931
TerraformRunner._args_for_remote
train
def _args_for_remote(self): """ Generate arguments for 'terraform remote config'. Return None if not present in configuration. :return: list of args for 'terraform remote config' or None :rtype: :std:term:`list` """ conf = self.config.get('terraform_remote_state'...
python
{ "resource": "" }
q45932
TerraformRunner.apply
train
def apply(self, stream=False): """ Run a 'terraform apply' :param stream: whether or not to stream TF output in realtime :type stream: bool """ self._setup_tf(stream=stream) try: self._taint_deployment(stream=stream) except Exception: ...
python
{ "resource": "" }
q45933
TerraformRunner._show_outputs
train
def _show_outputs(self): """ Print the terraform outputs. """ outs = self._get_outputs() print("\n\n" + '=> Terraform Outputs:') for k in sorted(outs): print('%s = %s' % (k, outs[k]))
python
{ "resource": "" }
q45934
TerraformRunner._get_outputs
train
def _get_outputs(self): """ Return a dict of the terraform outputs. :return: dict of terraform outputs :rtype: dict """ if self.tf_version >= (0, 7, 0): logger.debug('Running: terraform output') res = self._run_tf('output', cmd_args=['-json']) ...
python
{ "resource": "" }
q45935
TerraformRunner.destroy
train
def destroy(self, stream=False): """ Run a 'terraform destroy' :param stream: whether or not to stream TF output in realtime :type stream: bool """ self._setup_tf(stream=stream) args = ['-refresh=true', '-force', '.'] logger.warning('Running terraform des...
python
{ "resource": "" }
q45936
TerraformRunner._setup_tf
train
def _setup_tf(self, stream=False): """ Setup terraform; either 'remote config' or 'init' depending on version. """ if self.tf_version < (0, 9, 0): self._set_remote(stream=stream) return self._run_tf('init', stream=stream) logger.info('Terraform ini...
python
{ "resource": "" }
q45937
ConnectionPool.release
train
def release(self, conn): """Release a previously acquired connection. The connection is put back into the pool.""" self._pool_lock.acquire() self._pool.put(ConnectionWrapper(self._pool, conn)) self._current_acquired -= 1 self._pool_lock.release()
python
{ "resource": "" }
q45938
ConnectionPool.release_pool
train
def release_pool(self): """Release pool and all its connection""" if self._current_acquired > 0: raise PoolException("Can't release pool: %d connection(s) still acquired" % self._current_acquired) while not self._pool.empty(): conn = self.acquire() conn.close(...
python
{ "resource": "" }
q45939
SassLibraryEventHandler.index
train
def index(self): """ Reset inspector buffers and index project sources dependencies. This have to be executed each time an event occurs. Note: If a Boussole exception occurs during operation, it will be catched and an error flag will be set to ``True`` so event ...
python
{ "resource": "" }
q45940
SassLibraryEventHandler.compile_source
train
def compile_source(self, sourcepath): """ Compile source to its destination Check if the source is eligible to compile (not partial and allowed from exclude patterns) Args: sourcepath (string): Sass source path to compile to its destination using pro...
python
{ "resource": "" }
q45941
SassLibraryEventHandler.compile_dependencies
train
def compile_dependencies(self, sourcepath, include_self=False): """ Apply compile on all dependencies Args: sourcepath (string): Sass source path to compile to its destination using project settings. Keyword Arguments: include_self (bool): If ``T...
python
{ "resource": "" }
q45942
SassLibraryEventHandler.on_moved
train
def on_moved(self, event): """ Called when a file or a directory is moved or renamed. Many editors don't directly change a file, instead they make a transitional file like ``*.part`` then move it to the final filename. Args: event: Watchdog event, either ``watchdog....
python
{ "resource": "" }
q45943
SassLibraryEventHandler.on_created
train
def on_created(self, event): """ Called when a new file or directory is created. Todo: This should be also used (extended from another class?) to watch for some special name file (like ".boussole-watcher-stop" create to raise a KeyboardInterrupt, so we may be...
python
{ "resource": "" }
q45944
SassLibraryEventHandler.on_modified
train
def on_modified(self, event): """ Called when a file or directory is modified. Args: event: Watchdog event, ``watchdog.events.DirModifiedEvent`` or ``watchdog.events.FileModifiedEvent``. """ if not self._event_error: self.logger.info(u"Cha...
python
{ "resource": "" }
q45945
SassLibraryEventHandler.on_deleted
train
def on_deleted(self, event): """ Called when a file or directory is deleted. Todo: May be bugged with inspector and sass compiler since the does not exists anymore. Args: event: Watchdog event, ``watchdog.events.DirDeletedEvent`` or `...
python
{ "resource": "" }
q45946
hebrew_number
train
def hebrew_number(num, hebrew=True, short=False): """Return "Gimatria" number.""" if not hebrew: return str(num) if not 0 <= num < 10000: raise ValueError('num must be between 0 to 9999, got:{}'.format(num)) hstring = u"" if num >= 1000: hstring += htables.DIGITS[0][num // 10...
python
{ "resource": "" }
q45947
HDate.hdate
train
def hdate(self): """Return the hebrew date.""" if self._last_updated == "hdate": return self._hdate return conv.jdn_to_hdate(self._jdn)
python
{ "resource": "" }
q45948
HDate.hdate
train
def hdate(self, date): """Set the dates of the HDate object based on a given Hebrew date.""" # Sanity checks if date is None and isinstance(self.gdate, datetime.date): # Calculate the value since gdate has been set date = self.hdate if not isinstance(date, Hebrew...
python
{ "resource": "" }
q45949
HDate.gdate
train
def gdate(self): """Return the Gregorian date for the given Hebrew date object.""" if self._last_updated == "gdate": return self._gdate return conv.jdn_to_gdate(self._jdn)
python
{ "resource": "" }
q45950
HDate._jdn
train
def _jdn(self): """Return the Julian date number for the given date.""" if self._last_updated == "gdate": return conv.gdate_to_jdn(self.gdate) return conv.hdate_to_jdn(self.hdate)
python
{ "resource": "" }
q45951
HDate.hebrew_date
train
def hebrew_date(self): """Return the hebrew date string.""" return u"{} {} {}".format( hebrew_number(self.hdate.day, hebrew=self.hebrew), # Day htables.MONTHS[self.hdate.month - 1][self.hebrew], # Month hebrew_number(self.hdate.year, hebrew=self.hebrew))
python
{ "resource": "" }
q45952
HDate.holiday_description
train
def holiday_description(self): """ Return the holiday description. In case none exists will return None. """ entry = self._holiday_entry() desc = entry.description return desc.hebrew.long if self.hebrew else desc.english
python
{ "resource": "" }
q45953
HDate._holiday_entry
train
def _holiday_entry(self): """Return the abstract holiday information from holidays table.""" holidays_list = self.get_holidays_for_year() holidays_list = [ holiday for holiday, holiday_hdate in holidays_list if holiday_hdate.hdate == self.hdate ] assert le...
python
{ "resource": "" }
q45954
HDate.rosh_hashana_dow
train
def rosh_hashana_dow(self): """Return the Hebrew day of week for Rosh Hashana.""" jdn = conv.hdate_to_jdn(HebrewDate(self.hdate.year, Months.Tishrei, 1)) return (jdn + 1) % 7 + 1
python
{ "resource": "" }
q45955
HDate.pesach_dow
train
def pesach_dow(self): """Return the first day of week for Pesach.""" jdn = conv.hdate_to_jdn(HebrewDate(self.hdate.year, Months.Nisan, 15)) return (jdn + 1) % 7 + 1
python
{ "resource": "" }
q45956
HDate.omer_day
train
def omer_day(self): """Return the day of the Omer.""" first_omer_day = HebrewDate(self.hdate.year, Months.Nisan, 16) omer_day = self._jdn - conv.hdate_to_jdn(first_omer_day) + 1 if not 0 < omer_day < 50: return 0 return omer_day
python
{ "resource": "" }
q45957
HDate.next_day
train
def next_day(self): """Return the HDate for the next day.""" return HDate(self.gdate + datetime.timedelta(1), self.diaspora, self.hebrew)
python
{ "resource": "" }
q45958
HDate.previous_day
train
def previous_day(self): """Return the HDate for the previous day.""" return HDate(self.gdate + datetime.timedelta(-1), self.diaspora, self.hebrew)
python
{ "resource": "" }
q45959
HDate.upcoming_shabbat
train
def upcoming_shabbat(self): """Return the HDate for either the upcoming or current Shabbat. If it is currently Shabbat, returns the HDate of the Saturday. """ if self.is_shabbat: return self # If it's Sunday, fast forward to the next Shabbat. saturday = self....
python
{ "resource": "" }
q45960
HDate.upcoming_shabbat_or_yom_tov
train
def upcoming_shabbat_or_yom_tov(self): """Return the HDate for the upcoming or current Shabbat or Yom Tov. If it is currently Shabbat, returns the HDate of the Saturday. If it is currently Yom Tov, returns the HDate of the first day (rather than "leil" Yom Tov). To access Leil Yom Tov, ...
python
{ "resource": "" }
q45961
HDate.first_day
train
def first_day(self): """Return the first day of Yom Tov or Shabbat. This is useful for three-day holidays, for example: it will return the first in a string of Yom Tov + Shabbat. If this HDate is Shabbat followed by no Yom Tov, returns the Saturday. If this HDate is neither Yom ...
python
{ "resource": "" }
q45962
HDate.last_day
train
def last_day(self): """Return the last day of Yom Tov or Shabbat. This is useful for three-day holidays, for example: it will return the last in a string of Yom Tov + Shabbat. If this HDate is Shabbat followed by no Yom Tov, returns the Saturday. If this HDate is neither Yom Tov...
python
{ "resource": "" }
q45963
HDate.get_holidays_for_year
train
def get_holidays_for_year(self, types=None): """Get all the actual holiday days for a given HDate's year. If specified, use the list of types to limit the holidays returned. """ # Filter any non-related holidays depending on Israel/Diaspora only holidays_list = [ hol...
python
{ "resource": "" }
q45964
HDate.get_reading
train
def get_reading(self): """Return number of hebrew parasha.""" _year_type = (self.year_size() % 10) - 3 year_type = ( self.diaspora * 1000 + self.rosh_hashana_dow() * 100 + _year_type * 10 + self.pesach_dow()) _LOGGER.debug("Year type: %d",...
python
{ "resource": "" }
q45965
ls
train
def ls(ctx, available): "List installed datasets on path" path = ctx.obj['path'] global_ = ctx.obj['global_'] _ls(available=available, **ctx.obj)
python
{ "resource": "" }
q45966
reqs
train
def reqs(ctx, dataset, kwargs): "Get the dataset's pip requirements" kwargs = parse_kwargs(kwargs) (print)(data(dataset, **ctx.obj).reqs(**kwargs))
python
{ "resource": "" }
q45967
size
train
def size(ctx, dataset, kwargs): "Show dataset size" kwargs = parse_kwargs(kwargs) (print)(data(dataset, **ctx.obj).get(**kwargs).complete_set.size)
python
{ "resource": "" }
q45968
rm
train
def rm(ctx, dataset, kwargs): "removes the dataset's folder if it exists" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).rm(**kwargs)
python
{ "resource": "" }
q45969
rm_subsets
train
def rm_subsets(ctx, dataset, kwargs): "removes the dataset's training-set and test-set folders if they exists" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).rm_subsets(**kwargs)
python
{ "resource": "" }
q45970
extract
train
def extract(ctx, dataset, kwargs): "extracts the files from the compressed archives" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).extract(**kwargs)
python
{ "resource": "" }
q45971
rm_compressed
train
def rm_compressed(ctx, dataset, kwargs): "removes the compressed files" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).rm_compressed(**kwargs)
python
{ "resource": "" }
q45972
process
train
def process(ctx, dataset, kwargs): "processes the data to a friendly format" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).process(**kwargs)
python
{ "resource": "" }
q45973
rm_raw
train
def rm_raw(ctx, dataset, kwargs): "removes the raw unprocessed data" kwargs = parse_kwargs(kwargs) data(dataset, **ctx.obj).rm_raw(**kwargs)
python
{ "resource": "" }
q45974
write_moc_fits_hdu
train
def write_moc_fits_hdu(moc): """Create a FITS table HDU representation of a MOC. """ # Ensure data are normalized. moc.normalize() # Determine whether a 32 or 64 bit column is required. if moc.order < 14: moc_type = np.int32 col_type = 'J' else: moc_type = np.int64 ...
python
{ "resource": "" }
q45975
write_moc_fits
train
def write_moc_fits(moc, filename, **kwargs): """Write a MOC as a FITS file. Any additional keyword arguments are passed to the astropy.io.fits.HDUList.writeto method. """ tbhdu = write_moc_fits_hdu(moc) prihdr = fits.Header() prihdu = fits.PrimaryHDU(header=prihdr) hdulist = fits.HDULi...
python
{ "resource": "" }
q45976
read_moc_fits
train
def read_moc_fits(moc, filename, include_meta=False, **kwargs): """Read data from a FITS file into a MOC. Any additional keyword arguments are passed to the astropy.io.fits.open method. """ hl = fits.open(filename, mode='readonly', **kwargs) read_moc_fits_hdu(moc, hl[1], include_meta)
python
{ "resource": "" }
q45977
read_moc_fits_hdu
train
def read_moc_fits_hdu(moc, hdu, include_meta=False): """Read data from a FITS table HDU into a MOC. """ if include_meta: header = hdu.header if 'MOCTYPE' in header: moc.type = header['MOCTYPE'] if 'MOCID' in header: moc.id = header['MOCID'] if 'ORIGI...
python
{ "resource": "" }
q45978
_tracebacks
train
def _tracebacks(score_matrix, traceback_matrix, idx): """Implementation of traceeback. This version can produce empty tracebacks, which we generally don't want users seeing. So the higher level `tracebacks` filters those out. """ score = score_matrix[idx] if score == 0: yield () ...
python
{ "resource": "" }
q45979
tracebacks
train
def tracebacks(score_matrix, traceback_matrix, idx): """Calculate the tracebacks for `traceback_matrix` starting at index `idx`. Returns: An iterable of tracebacks where each traceback is sequence of (index, direction) tuples. Each `index` is an index into `traceback_matrix`. `direction` indicates ...
python
{ "resource": "" }
q45980
build_score_matrix
train
def build_score_matrix(a, b, score_func, gap_penalty): """Calculate the score and traceback matrices for two input sequences and scoring functions. Returns: A tuple of (score-matrix, traceback-matrix). Each entry in the score-matrix is a numeric score. Each entry in the traceback-matrix is a lo...
python
{ "resource": "" }
q45981
align
train
def align(a, b, score_func, gap_penalty): """Calculate the best alignments of sequences `a` and `b`. Arguments: a: The first of two sequences to align b: The second of two sequences to align score_func: A 2-ary callable which calculates the "match" score between two elements in the se...
python
{ "resource": "" }
q45982
unsubscribe
train
def unsubscribe(user_id, from_all=False, campaign_ids=None, on_error=None, on_success=None): """ Unsubscribe a user from some or all campaigns. :param str | number user_id: the id you use to identify a user. this should be static for the lifetime of a user. :param bool from_all True to unsubscribe fro...
python
{ "resource": "" }
q45983
subscribe
train
def subscribe(user_id, to_all=False, campaign_ids=None, on_error=None, on_success=None): """ Resubscribe a user to some or all campaigns. :param str | number user_id: the id you use to identify a user. this should be static for the lifetime of a user. :param bool to_all True to reubscribe to all campa...
python
{ "resource": "" }
q45984
disable_all_tokens
train
def disable_all_tokens(platform, user_id, on_error=None, on_success=None): """ Disable ALL device tokens for the given user on the specified platform. :param str platform The platform which to disable token on. One of either Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service (outb...
python
{ "resource": "" }
q45985
disable_token
train
def disable_token(platform, user_id, token, on_error=None, on_success=None): """ Disable a device token for a user. :param str platform The platform which to disable token on. One of either Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service (outbound.APNS). :param str | numbe...
python
{ "resource": "" }
q45986
register_token
train
def register_token(platform, user_id, token, on_error=None, on_success=None): """ Register a device token for a user. :param str platform The platform which to register token on. One of either Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service (outbound.APNS). :param str | nu...
python
{ "resource": "" }
q45987
alias
train
def alias(user_id, previous_id, on_error=None, on_success=None): """ Alias one user id to another. :param str | number user_id: the id you use to identify a user. this will be the user's primary user id. :param str | number previous_id: the id you previously used to identify a user (or the old user id...
python
{ "resource": "" }
q45988
identify
train
def identify(user_id, previous_id=None, group_id=None, group_attributes=None, first_name=None, last_name=None, email=None, phone_number=None, apns_tokens=None, gcm_tokens=None, attributes=None, on_error=None, on_success=None): """ Identifying a user creates a record of your user ...
python
{ "resource": "" }
q45989
track
train
def track(user_id, event, first_name=None, last_name=None, email=None, phone_number=None, apns_tokens=None, gcm_tokens=None, user_attributes=None, properties=None, on_error=None, on_success=None, timestamp=None): """ For any event you want to track, when a user triggers that event you would call...
python
{ "resource": "" }
q45990
SettingsBackendJson.parse
train
def parse(self, filepath, content): """ Parse opened settings content using JSON parser. Args: filepath (str): Settings object, depends from backend content (str): Settings content from opened file, depends from backend. Raises: bouss...
python
{ "resource": "" }
q45991
run_client
train
def run_client(ip, port, authkey, max_items=None, timeout=2): """Connect to a SwarmServer and do its dirty work. :param ip: ip address of server :param port: port to connect to on server :param authkey: authorization key :param max_items: maximum number of items to process from server. Usef...
python
{ "resource": "" }
q45992
worker
train
def worker(n): """Spend some time calculating exponentials.""" for _ in xrange(999999): a = exp(n) b = exp(2*n) return n, a
python
{ "resource": "" }
q45993
MyriadServer.imap_unordered
train
def imap_unordered(self, jobs, timeout=0.5): """A iterator over a set of jobs. :param jobs: the items to pass through our function :param timeout: timeout between polling queues Results are yielded as soon as they are available in the output queue (up to the discretisation prov...
python
{ "resource": "" }
q45994
Polypeptide.primitive
train
def primitive(self): """Primitive of the backbone. Notes ----- This is the average of the positions of all the CAs in frames of `sl` `Residues`. """ cas = self.get_reference_coords() primitive_coords = make_primitive_extrapolate_ends( cas, smo...
python
{ "resource": "" }
q45995
Polypeptide.fasta
train
def fasta(self): """Generates sequence data for the protein in FASTA format.""" max_line_length = 79 fasta_str = '>{0}:{1}|PDBID|CHAIN|SEQUENCE\n'.format( self.parent.id.upper(), self.id) seq = self.sequence split_seq = [seq[i: i + max_line_length] ...
python
{ "resource": "" }
q45996
Residue.centroid
train
def centroid(self): """Calculates the centroid of the residue. Returns ------- centroid : numpy.array or None Returns a 3D coordinate for the residue unless a CB atom is not available, in which case `None` is returned. Notes ----- ...
python
{ "resource": "" }
q45997
shutdown
train
def shutdown(server, graceful=True): """Shut down the application. If a graceful stop is requested, waits for all of the IO loop's handlers to finish before shutting down the rest of the process. We impose a 10 second timeout. Based on http://tornadogists.org/3428652/ """ ioloop = IOLoop.i...
python
{ "resource": "" }
q45998
HttpTransport.send
train
def send(self, alf): ''' Non-blocking send ''' send_alf = SendThread(self.url, alf, self.connection_timeout, self.retry_count) send_alf.start()
python
{ "resource": "" }
q45999
ScssInspector.inspect
train
def inspect(self, *args, **kwargs): """ Recursively inspect all given SCSS files to find imported dependencies. This does not return anything. Just fill internal buffers about inspected files. Note: This will ignore orphan files (files that are not imported from ...
python
{ "resource": "" }