_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q43800
iterate
train
def iterate(t_table, wordlist, stanzas, schemes, rprobs, maxsteps): """ Iterate EM and return final probabilities """ data_probs = numpy.zeros(len(stanzas)) old_data_probs = None probs = None num_words = len(wordlist) ctr = 0 for ctr in range(maxsteps): logging.info("Iterati...
python
{ "resource": "" }
q43801
print_results
train
def print_results(results, outfile): """ Write results to outfile """ for stanza_words, scheme in results: outfile.write(str(' ').join(stanza_words) + str('\n')) outfile.write(str(' ').join(map(str, scheme)) + str('\n\n')) outfile.close() logging.info("Wrote result")
python
{ "resource": "" }
q43802
main
train
def main(args_list=None): """ Wrapper for find_schemes if called from command line """ args_list = args_list or sys.argv[1:] parser = argparse.ArgumentParser(description='Discover schemes of given stanza file') parser.add_argument( 'infile', type=argparse.FileType('r'), ) ...
python
{ "resource": "" }
q43803
Stanza.set_word_indices
train
def set_word_indices(self, wordlist): """ Populate the list of word_indices, mapping self.words to the given wordlist """ self.word_indices = [wordlist.index(word) for word in self.words]
python
{ "resource": "" }
q43804
Schemes._parse_scheme_file
train
def _parse_scheme_file(self): """ Initialize redundant data structures for lookup optimization """ schemes = json.loads(self.scheme_file.read(), object_pairs_hook=OrderedDict) scheme_list = [] scheme_dict = defaultdict(list) for scheme_len, scheme_group in schemes...
python
{ "resource": "" }
q43805
Isort._create_output_from_match
train
def _create_output_from_match(self, match_result): """As isort outputs full path, we change it to relative path.""" full_path = match_result['full_path'] path = self._get_relative_path(full_path) return LinterOutput(self.name, path, match_result['msg'])
python
{ "resource": "" }
q43806
_generate_one_ephemeris
train
def _generate_one_ephemeris( cmd): """generate one orbfit ephemeris **Key Arguments:** - ``cmd`` -- the command to execute [cmd, object] **Return:** - ``results`` -- the single ephemeris results """ global cmdList cmd = cmdList[cmd] results = [] for c in cmd: ...
python
{ "resource": "" }
q43807
text
train
def text(short): """Compiles short markup text into an HTML strings""" return indent(short, branch_method=html_block_tag, leaf_method=convert_line, pass_syntax=PASS_SYNTAX, flush_left_syntax=FLUSH_LEFT_SYNTAX, flush_left_empty_line=FLUSH_LEFT_EMPTY_LINE, indentation_method=fi...
python
{ "resource": "" }
q43808
get_indented_block
train
def get_indented_block(prefix_lines): """Returns an integer. The return value is the number of lines that belong to block begun on the first line. Parameters ---------- prefix_lines : list of basestring pairs Each pair corresponds to a line of SHPAML source code. The first e...
python
{ "resource": "" }
q43809
indent
train
def indent(text, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block=get_indented_block): """Returns HTML as a basestring. Parameters ---------- text : basestring Source code, typically SHPAML, but could be a different (...
python
{ "resource": "" }
q43810
indent_lines
train
def indent_lines(lines, output, branch_method, leaf_method, pass_syntax, flush_left_syntax, flush_left_empty_line, indentation_method, get_block): """Returns None. The way this function produces output is by adding strings to the list that's passed in as the second parameter. Paramete...
python
{ "resource": "" }
q43811
_write_reqs
train
def _write_reqs(amend: bool = False, stage: bool = False): """ Writes the requirement files Args: amend: amend last commit with changes stage: stage changes """ LOGGER.info('writing requirements') base_cmd = 'pipenv lock -r' _write_reqs_file(f'{base_cmd}', 'requirements.txt...
python
{ "resource": "" }
q43812
reqs
train
def reqs(amend: bool = False, stage: bool = False): """ Write requirements files Args: amend: amend last commit with changes stage: stage changes """ changed_files = CTX.repo.changed_files() if 'requirements.txt' in changed_files or 'requirements-dev.txt' in changed_files: ...
python
{ "resource": "" }
q43813
chunks
train
def chunks(data, size): """ Generator that splits the given data into chunks """ for i in range(0, len(data), size): yield data[i:i + size]
python
{ "resource": "" }
q43814
Bot.connect
train
def connect(self, host, port=6667, password=None): """ Connects to a server """ # Prepare the callbacks self._irc.add_global_handler('all_events', self.__handler) # Prepare the connection self._connection = self._irc.server().connect( host, port, self...
python
{ "resource": "" }
q43815
Bot.__handler
train
def __handler(self, connection, event): """ Handles an IRC event """ try: # Find local handler method = getattr(self, "on_{0}".format(event.type)) except AttributeError: pass else: try: # Call it ...
python
{ "resource": "" }
q43816
Bot.close
train
def close(self): """ Disconnects from the server """ # Disconnect with a fancy message, then close connection if self._connection is not None: self._connection.disconnect("Bot is quitting") self._connection.close() self._connection = None ...
python
{ "resource": "" }
q43817
Bot.wait
train
def wait(self, timeout=None): """ Waits for the client to stop its loop """ self.__stopped.wait(timeout) return self.__stopped.is_set()
python
{ "resource": "" }
q43818
CommandBot.on_privmsg
train
def on_privmsg(self, connection, event): """ Got a message from a user """ sender = self.get_nick(event.source) message = event.arguments[0] if sender == 'NickServ': logging.info("Got message from NickServ: %s", message) if "password" in m...
python
{ "resource": "" }
q43819
CommandBot.handle_message
train
def handle_message(self, connection, sender, target, message): """ Handles a received message """ parts = message.strip().split(' ', 2) if parts and parts[0].lower() == '!bot': try: command = parts[1].lower() except IndexError: ...
python
{ "resource": "" }
q43820
CommandBot.on_invite
train
def on_invite(self, connection, event): """ Got an invitation to a channel """ sender = self.get_nick(event.source) invited = self.get_nick(event.target) channel = event.arguments[0] if invited == self._nickname: logging.info("! I am invited to %s by ...
python
{ "resource": "" }
q43821
CommandBot._handle_command
train
def _handle_command(self, connection, sender, target, command, payload): """ Handles a command, if any """ try: # Find the handler handler = getattr(self, "cmd_{0}".format(command)) except AttributeError: self.safe_send(connection, target, "Unk...
python
{ "resource": "" }
q43822
CommandBot.safe_send
train
def safe_send(self, connection, target, message, *args, **kwargs): """ Safely sends a message to the given target """ # Compute maximum length of payload prefix = "PRIVMSG {0} :".format(target) max_len = 510 - len(prefix) for chunk in chunks(message.format(*args,...
python
{ "resource": "" }
q43823
MessageBot.__notify
train
def __notify(self, sender, content): """ Calls back listener when a message is received """ if self.handle_message is not None: try: self.handle_message(sender, content) except Exception as ex: logging.exception("Error calling messa...
python
{ "resource": "" }
q43824
MessageBot._make_line
train
def _make_line(self, uid, command=None): """ Prepares an IRC line in Herald's format """ if command: return ":".join(("HRLD", command, uid)) else: return ":".join(("HRLD", uid))
python
{ "resource": "" }
q43825
MessageBot.send_message
train
def send_message(self, target, content, uid=None): """ Sends a message through IRC """ # Compute maximum length of payload prefix = "PRIVMSG {0} :".format(target) single_prefix = self._make_line("MSG:") single_prefix_len = len(single_prefix) max_len = 510 ...
python
{ "resource": "" }
q43826
Herald.__make_message
train
def __make_message(self, topic, content): """ Prepares the message content """ return {"uid": str(uuid.uuid4()).replace('-', '').upper(), "topic": topic, "content": content}
python
{ "resource": "" }
q43827
Herald._notify_listeners
train
def _notify_listeners(self, sender, message): """ Notifies listeners of a new message """ uid = message['uid'] msg_topic = message['topic'] self._ack(sender, uid, 'fire') all_listeners = set() for lst_topic, listeners in self.__listeners.items(): ...
python
{ "resource": "" }
q43828
Herald._ack
train
def _ack(self, sender, uid, level, payload=None): """ Replies to a message """ content = {'reply-to': uid, 'reply-level': level, 'payload': payload} self.__client.send_message(sender, json.dumps(content))
python
{ "resource": "" }
q43829
Herald.on_message
train
def on_message(self, sender, content): """ Got a message from the client """ try: message = json.loads(content) except (ValueError, TypeError) as ex: logging.error("Not a valid JSON string: %s", ex) return try: # Check the...
python
{ "resource": "" }
q43830
t_php_OBJECT_OPERATOR
train
def t_php_OBJECT_OPERATOR(t): r'->' if re.match(r'[A-Za-z_]', peek(t.lexer)): t.lexer.push_state('property') return t
python
{ "resource": "" }
q43831
Orchestrator.has_commit
train
def has_commit(self, client_key=None): """ Return True if client has new commit. :param client_key: The client key :type client_key: str :return: :rtype: boolean """ if client_key is None and self.current_client is None: raise ClientNotExist()...
python
{ "resource": "" }
q43832
init
train
def init(ciprcfg, env, console): """ Initialize a Corona project directory. """ ciprcfg.create() templ_dir = path.join(env.skel_dir, 'default') console.quiet('Copying files from %s' % templ_dir) for src, dst in util.sync_dir_to(templ_dir, env.project_directory, ignore_existing=True): ...
python
{ "resource": "" }
q43833
update
train
def update(env): """ Update an existing cipr project to the latest intalled version. """ files = [path.join(env.project_directory, 'cipr.lua')] for filename in files: if path.exists(filename): os.remove(filename) app.command.run(['init', env.project_directory])
python
{ "resource": "" }
q43834
install
train
def install(args, console, env, ciprcfg, opts): """ Install a package from github and make it available for use. """ if len(args) == 0: # Is this a cipr project? if ciprcfg.exists: # Install all the packages for this project console.quiet('Installing current proje...
python
{ "resource": "" }
q43835
packages
train
def packages(ciprcfg, env, opts, console): """ List installed packages for this project """ for name, source in ciprcfg.packages.items(): console.normal('- %s' % name) if opts.long_details: console.normal(' - directory: %s' % path.join(env.package_dir, name)) co...
python
{ "resource": "" }
q43836
run
train
def run(env): """ Run current project in the Corona Simulator """ os.putenv('CIPR_PACKAGES', env.package_dir) os.putenv('CIPR_PROJECT', env.project_directory) # `Corona Terminal` doesn't support spaces in filenames so we cd in and use '.'. cmd = AND( clom.cd(path.dirname(env.projec...
python
{ "resource": "" }
q43837
build
train
def build(env, ciprcfg, console): """ Build the current project for distribution """ os.putenv('CIPR_PACKAGES', env.package_dir) os.putenv('CIPR_PROJECT', env.project_directory) build_settings = path.join(env.project_directory, 'build.settings') with open(build_settings, 'r') as f: ...
python
{ "resource": "" }
q43838
packageipa
train
def packageipa(env, console): """ Package the built app as an ipa for distribution in iOS App Store """ ipa_path, app_path = _get_ipa(env) output_dir = path.dirname(ipa_path) if path.exists(ipa_path): console.quiet('Removing %s' % ipa_path) os.remove(ipa_path) zf = zipfile....
python
{ "resource": "" }
q43839
expanddotpaths
train
def expanddotpaths(env, console): """ Move files with dots in them to sub-directories """ for filepath in os.listdir(path.join(env.dir)): filename, ext = path.splitext(filepath) if ext == '.lua' and '.' in filename: paths, newfilename = filename.rsplit('.', 1) new...
python
{ "resource": "" }
q43840
Obj.change
train
def change(self, key, value): """Update any other attribute on the build object""" self.obj[key] = value self.changes.append("Updating build:{}.{}={}" .format(self.obj['name'], key, value)) return self
python
{ "resource": "" }
q43841
Obj.release
train
def release(self, lane, status, target=None, meta=None, svcs=None): """Set release information on a build""" if target not in (None, 'current', 'future'): raise ValueError("\nError: Target must be None, 'current', or 'future'\n") svcs, meta, lane = self._prep_for_release(lane, svcs...
python
{ "resource": "" }
q43842
Obj.promote
train
def promote(self, lane, svcs=None, meta=None): """promote a build so it is ready for an upper lane""" svcs, meta, lane = self._prep_for_release(lane, svcs=svcs, meta=meta) # iterate and mark as future release for svc in svcs: self.changes.append("Promoting: {}.release.futur...
python
{ "resource": "" }
q43843
Obj.add_info
train
def add_info(self, data): """add info to a build""" for key in data: # verboten if key in ('status','state','name','id','application','services','release'): raise ValueError("Sorry, cannot set build info with key of {}".format(key)) self.obj[key] = dat...
python
{ "resource": "" }
q43844
BaseField.localize_field
train
def localize_field(self, value): """ Method that must transform the value from object to localized string """ if self.default is not None: if value is None or value == '': value = self.default return value or ''
python
{ "resource": "" }
q43845
hitail
train
def hitail(E: np.ndarray, diffnumflux: np.ndarray, isimE0: np.ndarray, E0: np.ndarray, Bhf: np.ndarray, bh: float, verbose: int = 0): """ strickland 1993 said 0.2, but 0.145 gives better match to peak flux at 2500 = E0 """ Bh = np.empty_like(E0) for iE0 in np.arange(E0.size): Bh[i...
python
{ "resource": "" }
q43846
Diffusible.diffuse
train
def diffuse(self, *args): """ this is a dispatcher of diffuse implementation. Depending of the arguments used. """ mode = diffusingModeEnum.unknown if (isinstance(args[0], str) and (len(args) == 3)): # reveived diffuse(str, any, any) mode = diffus...
python
{ "resource": "" }
q43847
json_response
train
def json_response(data, status=200): """Return a JsonResponse. Make sure you have django installed first.""" from django.http import JsonResponse return JsonResponse(data=data, status=status, safe=isinstance(data, dict))
python
{ "resource": "" }
q43848
send_email_template
train
def send_email_template(slug, base_url=None, context=None, user=None, to=None, cc=None, bcc=None, attachments=None, headers=None, connection=None, fail_silently=False): """ Shortcut to send an email template. """ email_template = EmailTemplate.objects.get_for_slug(slug) email...
python
{ "resource": "" }
q43849
Trace.from_file
train
def from_file(filename): """Read in filename and creates a trace object. :param filename: path to nu(x|s)mv output file :type filename: str :return: """ trace = Trace() reached = False with open(filename) as fp: for line in fp.readlines(): ...
python
{ "resource": "" }
q43850
kwargs_helper
train
def kwargs_helper(kwargs): """This function preprocesses the kwargs dictionary to sanitize it.""" args = [] for param, value in kwargs.items(): param = kw_subst.get(param, param) args.append((param, value)) return args
python
{ "resource": "" }
q43851
GetDate
train
def GetDate(text=None, selected=None, **kwargs): """Prompt the user for a date. This will raise a Zenity Calendar Dialog for the user to pick a date. It will return a datetime.date object with the date or None if the user hit cancel. text - Text to be displayed in the calendar dialog. ...
python
{ "resource": "" }
q43852
GetFilename
train
def GetFilename(multiple=False, sep='|', **kwargs): """Prompt the user for a filename. This will raise a Zenity File Selection Dialog. It will return a list with the selected files or None if the user hit cancel. multiple - True to allow the user to select multiple files. sep - Token to u...
python
{ "resource": "" }
q43853
GetDirectory
train
def GetDirectory(multiple=False, selected=None, sep=None, **kwargs): """Prompt the user for a directory. This will raise a Zenity Directory Selection Dialog. It will return a list with the selected directories or None if the user hit cancel. multiple - True to allow the user to select multip...
python
{ "resource": "" }
q43854
GetSavename
train
def GetSavename(default=None, **kwargs): """Prompt the user for a filename to save as. This will raise a Zenity Save As Dialog. It will return the name to save a file as or None if the user hit cancel. default - The default name that should appear in the save as dialog. kwargs - Optional...
python
{ "resource": "" }
q43855
ErrorMessage
train
def ErrorMessage(text, **kwargs): """Show an error message dialog to the user. This will raise a Zenity Error Dialog with a description of the error. text - A description of the error. kwargs - Optional command line parameters for Zenity such as height, width, etc.""" args = ...
python
{ "resource": "" }
q43856
Progress
train
def Progress(text='', percentage=0, auto_close=False, pulsate=False, **kwargs): """Show a progress dialog to the user. This will raise a Zenity Progress Dialog. It returns a callback that accepts two arguments. The first is a numeric value of the percent complete. The second is a message about...
python
{ "resource": "" }
q43857
GetText
train
def GetText(text='', entry_text='', password=False, **kwargs): """Get some text from the user. This will raise a Zenity Text Entry Dialog. It returns the text the user entered or None if the user hit cancel. text - A description of the text to enter. entry_text - The initial value of the text en...
python
{ "resource": "" }
q43858
TextInfo
train
def TextInfo(filename=None, editable=False, **kwargs): """Show the text of a file to the user. This will raise a Zenity Text Information Dialog presenting the user with the contents of a file. It returns the contents of the text box. filename - The path to the file to show. editable - True if th...
python
{ "resource": "" }
q43859
parse
train
def parse(file_contents, file_name): """ This takes a list of filenames and their paths of expected yaml files and tried to parse them, erroring if there are any parsing issues. Args: file_contents (str): Contents of a yml file Raises: yaml.parser.ParserError: Raises an error if th...
python
{ "resource": "" }
q43860
GhostBase.get_or_create
train
def get_or_create(cls, **kwargs): ''' If a record matching the instance already exists in the database, then return it, otherwise create a new record. ''' q = cls._get_instance(**kwargs) if q: return q q = cls(**kwargs) _action_and_commit(q, se...
python
{ "resource": "" }
q43861
GhostBase.update
train
def update(cls, **kwargs): ''' If a record matching the instance id already exists in the database, update it. If a record matching the instance id does not already exist, create a new record. ''' q = cls._get_instance(**{'id': kwargs['id']}) if q: fo...
python
{ "resource": "" }
q43862
ResponseClassLegacyAccessor._get_instance
train
def _get_instance(self, **kwargs): '''Return the first existing instance of the response record. ''' return session.query(self.response_class).filter_by(**kwargs).first()
python
{ "resource": "" }
q43863
ResponseClassLegacyAccessor.update
train
def update(self, response, **kwargs): ''' If a record matching the instance already exists in the database, update it, else create a new record. ''' response_cls = self._get_instance(**kwargs) if response_cls: setattr(response_cls, self.column, self.accessor(r...
python
{ "resource": "" }
q43864
LocationResponseClassLegacyAccessor.update
train
def update(self, response, **kwargs): ''' If a record matching the instance already exists in the database, update both the column and venue column attributes, else create a new record. ''' response_cls = super( LocationResponseClassLegacyAccessor, self)._get_instance...
python
{ "resource": "" }
q43865
ServerCommon.common_update_sys
train
def common_update_sys(self): """ update system package """ try: sudo('apt-get update -y --fix-missing') except Exception as e: print(e) print(green('System package is up to date.')) print()
python
{ "resource": "" }
q43866
ServerCommon.common_config_nginx_ssl
train
def common_config_nginx_ssl(self): """ Convert nginx server from http to https """ if prompt(red(' * Change url from http to https (y/n)?'), default='n') == 'y': if not exists(self.nginx_ssl_dir): sudo('mkdir -p {0}'.format(self.nginx_ssl_dir)) ...
python
{ "resource": "" }
q43867
ServerCommon.common_install_apache2
train
def common_install_apache2(self): """ Install apache2 web server """ try: sudo('apt-get install apache2 -y') except Exception as e: print(e) print(green(' * Installed Apache2 in the system.')) print(green(' * Done')) print()
python
{ "resource": "" }
q43868
ServerCommon.common_install_python_env
train
def common_install_python_env(self): """ Install python virtualenv """ sudo('apt-get install python3 python3-pip -y') sudo('pip3 install virtualenv') run('virtualenv {0}'.format(self.python_env_dir)) print(green(' * Installed Python3 virtual environment in t...
python
{ "resource": "" }
q43869
storage.new_tmp
train
def new_tmp(self): """ Create a new temp file allocation """ self.tmp_idx += 1 return p.join(self.tmp_dir, 'tmp_' + str(self.tmp_idx))
python
{ "resource": "" }
q43870
storage.new_backup
train
def new_backup(self, src): """ Create a new backup file allocation """ backup_id_file = p.join(self.backup_dir, '.bk_idx') backup_num = file_or_default(backup_id_file, 1, int) backup_name = str(backup_num) + "_" + os.path.basename(src) backup_num += 1 file_put_contents(...
python
{ "resource": "" }
q43871
storage.begin
train
def begin(self): """ Begin a transaction """ if self.journal != None: raise Exception('Storage is already active, nested begin not supported') # under normal operation journal is deleted at end of transaction # if it does exist we need to roll back if os.path.isfile...
python
{ "resource": "" }
q43872
storage.do_action
train
def do_action(self, command, journal = True): """ Implementation for declarative file operations. """ cmd = 0; src = 1; path = 1; data = 2; dst = 2 if journal is True: self.journal.write(json.dumps(command['undo']) + "\n") self.journal.flush() d = command['do']...
python
{ "resource": "" }
q43873
storage.rollback
train
def rollback(self): """ Do journal rollback """ # Close the journal for writing, if this is an automatic rollback following a crash, # the file descriptor will not be open, so don't need to do anything. if self.journal != None: self.journal.close() self.journal = None #...
python
{ "resource": "" }
q43874
storage.commit
train
def commit(self, cont = False): """ Finish a transaction """ self.journal.close() self.journal = None os.remove(self.j_file) for itm in os.listdir(self.tmp_dir): os.remove(cpjoin(self.tmp_dir, itm)) if cont is True: self.begin()
python
{ "resource": "" }
q43875
storage.file_get_contents
train
def file_get_contents(self, path): """ Returns contents of file located at 'path', not changing FS so does not require journaling """ with open(self.get_full_file_path(path), 'r') as f: return f.read()
python
{ "resource": "" }
q43876
storage.move_file
train
def move_file(self, src, dst): """ Move file from src to dst """ src = self.get_full_file_path(src); dst = self.get_full_file_path(dst) # record where file moved if os.path.isfile(src): # if destination file exists, copy it to tmp first if os.path.isfile(dst): ...
python
{ "resource": "" }
q43877
storage.delete_file
train
def delete_file(self, path): """ delete a file """ path = self.get_full_file_path(path) # if file exists, create a temp copy to allow rollback if os.path.isfile(path): tmp_path = self.new_tmp() self.do_action({ 'do' : ['move', path, tmp_path], ...
python
{ "resource": "" }
q43878
parse_sysctl
train
def parse_sysctl(text): ''' Parse sysctl output. ''' lines = text.splitlines() results = {} for line in lines: key, _, value = line.decode('ascii').partition(': ') if key == 'hw.memsize': value = int(value) elif key == 'vm.swapusage': values = value.spli...
python
{ "resource": "" }
q43879
parse_vmstat
train
def parse_vmstat(text): ''' Parse vmstat output. ''' lines = text.splitlines() results = Info() # TODO use MemInfo try: PAGESIZE = int(lines[0].split()[-2]) except IndexError: PAGESIZE = 4096 for line in lines[1:]: # dump header if not line[0] == 80: # b'P' star...
python
{ "resource": "" }
q43880
get_base_url
train
def get_base_url(html: str) -> str: """ Search for login url from VK login page """ forms = BeautifulSoup(html, 'html.parser').find_all('form') if not forms: raise VVKBaseUrlException('Form for login not found') elif len(forms) > 1: raise VVKBaseUrlException('More than one login ...
python
{ "resource": "" }
q43881
get_url_params
train
def get_url_params(url: str, fragment: bool = False) -> dict: """ Parse URL params """ parsed_url = urlparse(url) if fragment: url_query = parse_qsl(parsed_url.fragment) else: url_query = parse_qsl(parsed_url.query) return dict(url_query)
python
{ "resource": "" }
q43882
check_page_for_warnings
train
def check_page_for_warnings(html: str) -> None: """ Checks if is any warnings on page if so raises an exception """ soup = BeautifulSoup(html, 'html.parser') warnings = soup.find_all('div', {'class': 'service_msg_warning'}) if warnings: exception_msg = '; '.join((warning.get_text() for w...
python
{ "resource": "" }
q43883
get_column_keys_and_names
train
def get_column_keys_and_names(table): """ Return a generator of tuples k, c such that k is the name of the python attribute for the column and c is the name of the column in the sql table. """ ins = inspect(table) return ((k, c.name) for k, c in ins.mapper.c.items())
python
{ "resource": "" }
q43884
is_modified
train
def is_modified(row, dialect): """ Has the row data been modified? This method inspects the row, and iterates over all columns looking for changes to the (processed) data, skipping over unmodified columns. :param row: SQLAlchemy model instance :param dialect: :py:class:`~sqlalchemy.engine.inte...
python
{ "resource": "" }
q43885
registerLoggers
train
def registerLoggers(info, error, debug): """ Add logging functions to this module. Functions will be called on various severities (log, error, or debug respectively). Each function must have the signature: fn(message, **kwargs) If Python str.format()-style placeholders are in message,...
python
{ "resource": "" }
q43886
background
train
def background(cl, proto=EchoProcess, **kw): """ Use the reactor to run a process in the background. Keep the pid around. ``proto'' may be any callable which returns an instance of ProcessProtocol """ if isinstance(cl, basestring): cl = shlex.split(cl) if not cl[0].startswith('/')...
python
{ "resource": "" }
q43887
runner
train
def runner(Options, buffering=True): """ Return a standard "run" function that wraps an Options class If buffering=False, turn off stdout/stderr buffering for this process """ def run(argv=None): if not buffering: sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) s...
python
{ "resource": "" }
q43888
DayCare.killall
train
def killall(self): """ Kill all children """ for pid in set(self): try: os.kill(pid, signal.SIGTERM) except OSError, e: # pragma: nocover if e.errno == errno.ESRCH: "Process previously died on its own" ...
python
{ "resource": "" }
q43889
EchoProcess.processEnded
train
def processEnded(self, reason): """ Connected process shut down """ log_debug("{name} process exited", name=self.name) if self.deferred: if reason.type == ProcessDone: self.deferred.callback(reason.value.exitCode) elif reason.type == Proces...
python
{ "resource": "" }
q43890
EchoProcess.errReceived
train
def errReceived(self, data): """ Connected process wrote to stderr """ lines = data.splitlines() for line in lines: log_error("*** {name} stderr *** {line}", name=self.name, line=self.errFilter(line))
python
{ "resource": "" }
q43891
EchoProcess.outLineReceived
train
def outLineReceived(self, line): """ Handle data via stdout linewise. This is useful if you turned off buffering. In your subclass, override this if you want to handle the line as a protocol line in addition to logging it. (You may upcall this function safely.) "...
python
{ "resource": "" }
q43892
Tee.write
train
def write(self, *a, **kw): """ Write to both files If either one has an error, try writing the error to the other one. """ fl = None try: self.file1.write(*a, **kw) self.file1.flush() except IOError: badFile, fl = 1, failure.Fa...
python
{ "resource": "" }
q43893
from_etree
train
def from_etree( el, node=None, node_cls=None, tagsub=functools.partial(re.sub, r'\{.+?\}', ''), Node=Node): '''Convert the element tree to a tater tree. ''' node_cls = node_cls or Node if node is None: node = node_cls() tag = tagsub(el.tag) attrib = dict((tagsub(k), v) for (k...
python
{ "resource": "" }
q43894
secure
train
def secure(view): """ Authentication decorator for views. If DEBUG is on, we serve the view without authenticating. Default is 'django.contrib.auth.decorators.login_required'. Can also be 'django.contrib.admin.views.decorators.staff_member_required' or a custom decorator. """ auth_decor...
python
{ "resource": "" }
q43895
get_netid_categories
train
def get_netid_categories(netid, category_codes): """ Return a list of uwnetid.models Category objects corresponding to the netid and category code or list provided """ url = _netid_category_url(netid, category_codes) response = get_resource(url) return _json_to_categories(response)
python
{ "resource": "" }
q43896
update_catagory
train
def update_catagory(netid, category_code, status): """ Post a subscriptionfor the given netid and category_code """ url = "{0}/category".format(url_version()) body = { "categoryCode": category_code, "status": status, "categoryList": [{"netid": netid}] } response ...
python
{ "resource": "" }
q43897
_netid_category_url
train
def _netid_category_url(netid, category_codes): """ Return UWNetId resource for provided netid and category code or code list """ return "{0}/{1}/category/{2}".format( url_base(), netid, (','.join([str(n) for n in category_codes]) if isinstance(category_codes, (list, tuple))...
python
{ "resource": "" }
q43898
_json_to_categories
train
def _json_to_categories(response_body): """ Returns a list of Category objects """ data = json.loads(response_body) categories = [] for category_data in data.get("categoryList", []): categories.append(Category().from_json( data.get('uwNetID'), category_data)) return cate...
python
{ "resource": "" }
q43899
ParseContext.activate
train
def activate(ctx): """Activate the given ParseContext.""" if hasattr(ctx, '_on_context_exit'): raise ContextError( 'Context actions registered outside this ' 'parse context are active') try: ParseContext._active.append(ctx) ctx...
python
{ "resource": "" }