_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q54700
ProjectsExplorer.__rename_directory
train
def __rename_directory(self, source, target): """ Renames a directory using given source and target names. :param source: Source file. :type source: unicode :param target: Target file. :type target: unicode """ for node in itertools.chain(self.__script_e...
python
{ "resource": "" }
q54701
ProjectsExplorer.__delete_file
train
def __delete_file(self, file): """ Deletes given file. :param file: File to delete. :type file: unicode """ for file_node in self.__script_editor.model.get_file_nodes(file, self.__script_editor.model.root_node): self.__script_editor.unregister_node_path(file...
python
{ "resource": "" }
q54702
ProjectsExplorer.__delete_directory
train
def __delete_directory(self, directory): """ Deletes given directory. :param directory: Directory to delete. :type directory: unicode """ for node in itertools.chain(self.__script_editor.model.get_project_nodes(directory), self.__scri...
python
{ "resource": "" }
q54703
ProjectsExplorer.remove_project
train
def remove_project(self, node): """ Removes the project associated with given node. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Method success. :rtype: bool """ if node.family == "Project": self.__script_e...
python
{ "resource": "" }
q54704
ProjectsExplorer.add_new_file
train
def add_new_file(self, node): """ Adds a new file next to given Node associated path. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Method success. :rtype: bool """ if self.__script_editor.model.is_authoring_node(node):...
python
{ "resource": "" }
q54705
ProjectsExplorer.add_new_directory
train
def add_new_directory(self, node): """ Adds a new directory next to given Node associated path. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Method success. :rtype: bool """ if self.__script_editor.model.is_authoring_n...
python
{ "resource": "" }
q54706
ProjectsExplorer.rename
train
def rename(self, node): """ Renames given Node associated path. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Method success. :rtype: bool """ source = node.path base_name, state = QInputDialog.getText(self, "Re...
python
{ "resource": "" }
q54707
ProjectsExplorer.delete
train
def delete(self, node): """ Deletes given Node associated path. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Method success. :rtype: bool """ path = node.path if self.__script_editor.model.is_authoring_node(nod...
python
{ "resource": "" }
q54708
Model.get_object_by_global_id
train
def get_object_by_global_id(global_id): """ Find object by GlobalID and return appropriate model instance. """ app_name, tail = global_id.split('/', 1) model_name, object_id = tail.split('#', 1) path_to_controller = "{}/controllers/{}".format(app_name, model_name.lower())...
python
{ "resource": "" }
q54709
SQSolarcell._to_dict
train
def _to_dict(self): """ Return a dictionary representation of the current object. """ physical_prop_names = find_PhysicalProperty(self) physical_prop_vals = [getattr(self, prop) for prop in physical_prop_names] return dict(zip(physical_prop_names, physical_prop_vals))
python
{ "resource": "" }
q54710
SQSolarcell.calc_efficiency
train
def calc_efficiency(self): """ Solar cell efficiency The efficiency is calculated according to Shockley & Queisser's :cite:`10.1063/1.1736034` Eq. 2.8. This method returns a :class:`float`. """ cell_power = self.calc_power_density() solar_power = self.calc_blackbody_radi...
python
{ "resource": "" }
q54711
nodes
train
def nodes(): ''' List running nodes on all enabled cloud providers. Automatically flushes caches ''' for name, provider in env.providers.items(): print name provider.nodes() print
python
{ "resource": "" }
q54712
create
train
def create(provider, count=1, name=None, **kwargs): r''' Create one or more cloud servers Args: * provider (str): Cloud provider, e.g. ec2, digitalocean * count (int) =1: Number of instances * name (str) =None: Name of server(s) * \**kwargs: Provider-specific flags ''' ...
python
{ "resource": "" }
q54713
pricing
train
def pricing(sort='cost', **kwargs): ''' Print pricing tables for all enabled providers ''' for name, provider in env.providers.items(): print name provider.pricing(sort, **kwargs) print
python
{ "resource": "" }
q54714
getConParams
train
def getConParams(virtualhost): """ Connection object builder. Args: virtualhost (str): selected virtualhost in rabbitmq Returns: pika.ConnectionParameters: object filled by `constants` from :class:`edeposit.amqp.settings`. """ return pika.ConnectionParameters( h...
python
{ "resource": "" }
q54715
AMQPDaemon.onMessageReceived
train
def onMessageReceived(self, method_frame, properties, body): """ React to received message - deserialize it, add it to users reaction function stored in ``self.react_fn`` and send back result. If `Exception` is thrown during process, it is sent back instead of message. ...
python
{ "resource": "" }
q54716
AMQPDaemon.get_sendback
train
def get_sendback(self, uuid, key): """ Return function for sending progress messages back to original caller. Args: uuid (str): UUID of the received message. key (str): Routing key. Returns: fn reference: Reference to function which takes only one da...
python
{ "resource": "" }
q54717
AMQPDaemon.process_exception
train
def process_exception(self, e, uuid, routing_key, body, tb=None): """ Callback called when exception was raised. This method serializes the exception and sends it over AMQP back to caller. Args: e (obj): Instance of the exception. uuid (str): UUID of the...
python
{ "resource": "" }
q54718
QTLScan.pvalues
train
def pvalues(self): """Association p-value for candidate markers.""" self.compute_statistics() lml_alts = self.alt_lmls() lml_null = self.null_lml() lrs = -2 * lml_null + 2 * asarray(lml_alts) from scipy.stats import chi2 chi2 = chi2(df=1) return chi2.s...
python
{ "resource": "" }
q54719
SearchAndReplace.insert_pattern
train
def insert_pattern(pattern, model, index=0): """ Inserts given pattern into given Model. :param pattern: Pattern. :type pattern: unicode :param model: Model. :type model: PatternsModel :param index: Insertion indes. :type index: int :return: Metho...
python
{ "resource": "" }
q54720
SearchAndReplace.search
train
def search(self): """ Searchs current editor Widget for search pattern. :return: Method success. :rtype: bool """ editor = self.__container.get_current_editor() search_pattern = self.Search_comboBox.currentText() replacement_pattern = self.Replace_With_c...
python
{ "resource": "" }
q54721
ActionsManager.__normalize_name
train
def __normalize_name(self, name): """ Normalizes given action name. :param name: Action name. :type name: unicode :return: Normalized name. :rtype: bool """ if not name.startswith(self.__root_namespace): name = foundations.namespace.set_names...
python
{ "resource": "" }
q54722
ActionsManager.get
train
def get(self, action, default=None): """ Returns given action value. :param action: Action name. :type action: unicode :param default: Default value if action is not found. :type default: object :return: Action. :rtype: QAction """ try: ...
python
{ "resource": "" }
q54723
ActionsManager.list_actions
train
def list_actions(self): """ Returns the registered actions. :return: Actions list. :rtype: list """ actions = [] for path, actionName, action in self: actions.append(self.__namespace_splitter.join(itertools.chain(path, (actionName,)))) return...
python
{ "resource": "" }
q54724
ActionsManager.get_category
train
def get_category(self, name, vivify=False): """ Returns requested category. :param name: Category to retrieve. :type name: unicode :param vivify: Vivify missing parents in the chain to the requested category. :type vivify: bool :return: Category. :rtype: ...
python
{ "resource": "" }
q54725
ActionsManager.add_to_category
train
def add_to_category(self, category, name, action): """ Adds given action to given category. :param category: Category to store the action. :type category: unicode :param name: Action name. :type name: unicode :param action: Action object. :type action: QA...
python
{ "resource": "" }
q54726
ActionsManager.remove_from_category
train
def remove_from_category(self, category, name): """ Removes given action from given category. :param category: Category to remove the action from. :type category: unicode :param name: Action name. :type name: unicode :return: Method success. :rtype: bool ...
python
{ "resource": "" }
q54727
ActionsManager.register_action
train
def register_action(self, name, **kwargs): """ Registers given action name, optional arguments like a parent, icon, slot etc ... can be given. :param name: Action to register. :type name: unicode :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* :retu...
python
{ "resource": "" }
q54728
ActionsManager.unregister_action
train
def unregister_action(self, name): """ Unregisters given action name. :param name: Action to register. :type name: unicode :return: Method success. :rtype: bool """ name = self.__normalize_name(name) action = self.get_action(name) if not ...
python
{ "resource": "" }
q54729
ActionsManager.is_shortcut_in_use
train
def is_shortcut_in_use(self, shortcut): """ Returns if given action shortcut is in use. :param name: Action shortcut. :type name: unicode :return: Is shortcut in use. :rtype: bool """ for path, actionName, action in foundations.walkers.dictionaries_walke...
python
{ "resource": "" }
q54730
ActionsManager.get_shortcut
train
def get_shortcut(self, name): """ Returns given action shortcut. :param name: Action to retrieve the shortcut. :type name: unicode :return: Action shortcut. :rtype: unicode """ name = self.__normalize_name(name) action = self.get_action(name) ...
python
{ "resource": "" }
q54731
ActionsManager.set_shortcut
train
def set_shortcut(self, name, shortcut): """ Sets given action shortcut. :param name: Action to set the shortcut. :type name: unicode :param shortcut: Shortcut to set. :type shortcut: unicode :return: Method success. :rtype: bool """ name ...
python
{ "resource": "" }
q54732
workspace_from_dir
train
def workspace_from_dir(directory, recurse=True): """ Construct a workspace object from a directory name. If recurse=True, this function will search down the directory tree and return the first workspace it finds. If recurse=False, an exception will be raised if the given directory is not a workspa...
python
{ "resource": "" }
q54733
root_from_dir
train
def root_from_dir(directory, recurse=True): """ Similar to workspace_from_dir, but this returns the root directory of a workspace rather than a workspace object. """ directory = os.path.abspath(directory) pickle_path = os.path.join(directory, 'workspace.pkl') # Make sure the given directo...
python
{ "resource": "" }
q54734
Workspace.largest_loop
train
def largest_loop(self): """ Return the boundaries for the largest loop segment. This is just meant to be a reasonable default for various selectors and filters to work with, in the case that more than one loop is being modeled. If you want to be more precise, you'll h...
python
{ "resource": "" }
q54735
Workspace.find_path
train
def find_path(self, basename, install_dir=None): """ Look in a few places for a file with the given name. If a custom version of the file is found in the directory being managed by this workspace, return it. Otherwise look in the custom and default input directories in the roo...
python
{ "resource": "" }
q54736
Workspace.cd
train
def cd(self, *subpaths): """ Change the current working directory and update all the paths in the workspace. This is useful for commands that have to be run from a certain directory. """ target = os.path.join(*subpaths) os.chdir(target)
python
{ "resource": "" }
q54737
validate
train
def validate(opts): """ Client-facing validate method. Checks to see if the passed int opts argument is either a string or a namespace containing the attribute 'wrapper' and runs validations on it accordingly. Note: this function currently does NOT support Unicode/Byte style strings, will need ...
python
{ "resource": "" }
q54738
parse_http_header
train
def parse_http_header(header_line): """Parse an HTTP header from a string, and return an ``HttpHeader``. ``header_line`` should only contain one line. ``BadHttpHeaderError`` is raised if the string is an invalid header line. """ header_line = header_line.decode().strip() col_idx = header_line....
python
{ "resource": "" }
q54739
methods
train
def methods(method_list): """A decorator to mark HTTP methods a resource can handle. For example:: class SomeRes(UrlResource): ... @methods(['GET', 'HEAD']) def handle_request(self, req): ... @handle_request.methods(['POST']) ...
python
{ "resource": "" }
q54740
HttpMessage.write_headers
train
def write_headers(self): """Construct headers in string form, and return a list containing each line of header strings. """ hlist = [] for h in self.headers: hlist.append("{}: {}".format(h.key, h.value)) return hlist
python
{ "resource": "" }
q54741
HttpRequest.respond
train
def respond(self, code): """Starts a response. ``code`` is an integer standing for standard HTTP status code. This method will automatically adjust the response to adapt to request parameters, such as "Accept-Encoding" and "TE". """ # TODO: respect encodings etc. in th...
python
{ "resource": "" }
q54742
HttpRequest.parse
train
def parse(cls, conn): """Read a request from the HTTP connection ``conn``. May raise ``BadHttpRequestError``. """ req = cls(conn) req_line = yield from conn.reader.readline() logger('HttpRequest').debug('req_line = %r', req_line) req._parse_req_line(req_line) ...
python
{ "resource": "" }
q54743
HttpResponse.write
train
def write(self): """Construct the response header. The return value is a list containing the whole response header, with each line as a list element. """ slist = [] slist.append('{}/{}.{} {} {}'.format( self.protocol, self...
python
{ "resource": "" }
q54744
HttpResponse.send
train
def send(self): """Send the response header, including the status line and all the HTTP headers. """ if hasattr(self, 'request'): self.request.responded = True self.connection.writer.write(str(self).encode()) yield from self.connection.writer.drain()
python
{ "resource": "" }
q54745
HttpResponse.send_body
train
def send_body(self, data): """Send the response body. ``data`` should be a bytes-like object or a string. """ if type(data) is str: data = data.encode() self.connection.writer.write(data) yield from self.connection.writer.drain()
python
{ "resource": "" }
q54746
polygonOffsetAndDistanceToPoint
train
def polygonOffsetAndDistanceToPoint(point, polygon, perpendicular=False): """Return the offset and the distancefrom the polygon start where the distance to point is minimal""" p = point s = polygon seen = 0 minDist = 1e400 minOffset = INVALID_DISTANCE for i in range(len(s) - 1): pos ...
python
{ "resource": "" }
q54747
distancePointToPolygon
train
def distancePointToPolygon(point, polygon, perpendicular=False): """Return the minimum distance between point and polygon""" p = point s = polygon minDist = None for i in range(0, len(s) - 1): dist = distancePointToLine(p, s[i], s[i + 1], perpendicular) if dist == INVALID_DISTANCE an...
python
{ "resource": "" }
q54748
Deferred.add_callbacks
train
def add_callbacks(self, callback, errback=None, callback_args=None, callback_kwargs=None, errback_args=None, errback_kwargs=None): """Add a callback and errback to the callback chain. If the previous callback succeeds the return value is passed as the ...
python
{ "resource": "" }
q54749
Deferred.add_callback
train
def add_callback(self, callback, *callback_args, **callback_kwargs): """Add a callback without an associated errback.""" return self.add_callbacks(callback, callback_args=callback_args, callback_kwargs=callback_kwargs)
python
{ "resource": "" }
q54750
Deferred.add_errback
train
def add_errback(self, errback, *errback_args, **errback_kwargs): """Add a errback without an associated callback.""" return self.add_callbacks(None, errback=errback, errback_args=errback_args, errback_kwargs=errback_kwargs)
python
{ "resource": "" }
q54751
Deferred.errback
train
def errback(self, result): """Begin the callback chain with the first errback. result -- A BaseException derivative. """ assert(isinstance(result, BaseException)) self._start_callbacks(result, True)
python
{ "resource": "" }
q54752
Deferred.result
train
def result(self, timeout=None): """Return the last result of the callback chain or raise the last exception thrown and not caught by an errback. This will block until the result is available. If a timeout is given and the call times out raise a TimeoutError If SIGINT i...
python
{ "resource": "" }
q54753
Deferred._do_wait
train
def _do_wait(self, timeout): """Wait for the deferred to be completed for a period of time Raises TimeoutError if the wait times out before the future is done. Raises CancelledError if the future is cancelled before the timeout is done. """ if self._cancelled: ...
python
{ "resource": "" }
q54754
Deferred._start_callbacks
train
def _start_callbacks(self, result, exception): """Perform the callback chain going back and forth between the callback and errback as needed. If an exception is raised and the entire chain is gone through without a valid errback then its simply logged. """ if self._canc...
python
{ "resource": "" }
q54755
Deferred._do_callbacks
train
def _do_callbacks(self): """Perform the callbacks.""" self._done = False while self._callbacks and not self._cancelled: cb, eb, cb_args, cb_kwargs, eb_args, eb_kwargs = self._callbacks.pop() if cb and not self._exception: try: self._re...
python
{ "resource": "" }
q54756
File.clean
train
def clean(self, value): """Takes a Werkzeug FileStorage, returns the relative path. """ if isinstance(value, FileStorage): return self.storage.save(value) return value
python
{ "resource": "" }
q54757
optimal_AR_spectrum
train
def optimal_AR_spectrum(dx, Y, ndegrees=None,return_min=True): ''' Get the optimal order AR spectrum by minimizing the BIC. ''' if ndegrees is None : ndegrees=len(Y)-ndegrees aicc=np.arange(ndegrees) aic=aicc.copy() bic=aicc.copy() tmpStr=[] for i in np.arange(1,...
python
{ "resource": "" }
q54758
server
train
def server(port): """Start the Django dev server.""" args = ['python', 'manage.py', 'runserver'] if port: args.append(port) run.main(args)
python
{ "resource": "" }
q54759
log_level
train
def log_level(conf): """Get debug settings from arguments. --debug: turn on additional debug code/inspection (implies logging.DEBUG) --verbose: turn up logging output (logging.DEBUG) --quiet: turn down logging output (logging.WARNING) Default is logging.INFO """ if conf.debu...
python
{ "resource": "" }
q54760
configure
train
def configure(conf, default_config=None): """Configure logging based on log config file. Turn on console logging if no logging files found :param conf: object with configuration namespace (argparse parser) """ if conf.logconfig and os.path.isfile(conf.logconfig): logging.config.fileConfig(...
python
{ "resource": "" }
q54761
_get_debug_formatter
train
def _get_debug_formatter(conf): """Get debug formatter based on configuration. :param conf: configurtration namespace (ex. argparser) --debug: log line numbers, file data --verbose: standard log format at a DEBUG loglevel --quiet: turn down logging output (logging.WARNING) default is logging.I...
python
{ "resource": "" }
q54762
init_console_logging
train
def init_console_logging(conf): """Log to console.""" # define a Handler which writes messages to the sys.stderr console = find_console_handler(logging.getLogger()) if not console: console = logging.StreamHandler() logging_level = log_level(conf) console.setLevel(logging_level) # se...
python
{ "resource": "" }
q54763
find_console_handler
train
def find_console_handler(logger): """Return a stream handler, if it exists.""" for handler in logger.handlers: if (isinstance(handler, logging.StreamHandler) and handler.stream == sys.stderr): return handler
python
{ "resource": "" }
q54764
DebugFormatter.format
train
def format(self, record): """Print out any 'extra' data provided in logs.""" if hasattr(record, 'data'): return "%s. DEBUG DATA=%s" % ( logging.Formatter.format(self, record), record.__dict__['data']) return logging.Formatter.format(self, record)
python
{ "resource": "" }
q54765
_find_key_cols
train
def _find_key_cols(df): """Identify columns in a DataFrame that could be a unique key""" keys = [] for col in df: if len(df[col].unique()) == len(df[col]): keys.append(col) return keys
python
{ "resource": "" }
q54766
HtmlAttributeHolder.add
train
def add(self, key, value): """ Creates a space separated string of attributes. Mostly for the "class" attribute. """ if key.endswith('_'): key = key[:-1] if key in self.attributes: self.attributes[key] = self.attributes[key] + ' ' + value ...
python
{ "resource": "" }
q54767
short_key
train
def short_key(): """ Generate a short key. >>> key = short_key() >>> len(key) 5 """ firstlast = list(ascii_letters + digits) middle = firstlast + list('-_') return ''.join(( choice(firstlast), choice(middle), choice(middle), choice(middle), choice(firstlast), ))
python
{ "resource": "" }
q54768
init_datastore
train
def init_datastore(config): """ Take the config definition and initialize the datastore. The config must contain either a 'datastore' parameter, which will be simply returned, or must contain a 'factory' which is a callable or entry point definition. The callable should take the remainder of ...
python
{ "resource": "" }
q54769
DataStore.store
train
def store( self, type, nick, time, fmt=None, code=None, filename=None, mime=None, data=None, makeshort=True): """ Store code or a file. Returns a tuple containing the uid and shortid """ uid = str(uuid.uuid4()) shortid = short_key() if makeshort else None ...
python
{ "resource": "" }
q54770
DataStore.build_paste
train
def build_paste(uid, shortid, type, nick, time, fmt, code, filename, mime): "Build a 'paste' object" return locals()
python
{ "resource": "" }
q54771
DataStore.migrate
train
def migrate(dest_datastore, source_datastore): """ Copy all records from source_datastore to dest_datastore """ for uid in source_datastore.list(): try: paste = source_datastore._retrieve(uid) except Exception as exc: print( ...
python
{ "resource": "" }
q54772
MarketDataInterface.get_brokendate_fx_forward_rate
train
def get_brokendate_fx_forward_rate(self, asset_manager_id, asset_id, price_date, value_date): """ This method takes calculates broken date forward FX rate based on the passed in parameters """ self.logger.info('Calculate broken date FX Forward - Asset Manager: %s - Asset (currency): %s ...
python
{ "resource": "" }
q54773
MarketDataInterface.last_available_business_date
train
def last_available_business_date(self, asset_manager_id, asset_ids, page_no=None, page_size=None): """ Returns the last available business date for the assets so we know the starting date for new data which needs to be downloaded from data providers. This method can only be inv...
python
{ "resource": "" }
q54774
readddl
train
def readddl(db): '''Walks down database objects and generates JDOC objects for table descriptions''' jdoc = [] for schema in db.contents: j = JDOC(None, schema.object_name, schema.comment, schema.object_type) jdoc.append(j) for t...
python
{ "resource": "" }
q54775
Bleach.run
train
def run(self, files, stack): "Clean your text" for filename, post in files.items(): post.content = self.bleach.clean(post.content, *self.args, **self.kwargs)
python
{ "resource": "" }
q54776
remove
train
def remove(addon, dev): """Remove a dependency. Examples: $ django remove dynamic-rest - dynamic-rest == 1.5.0 """ application = get_current_application() application.remove(addon, dev=dev)
python
{ "resource": "" }
q54777
MyAppFrame.show_tree
train
def show_tree(self, has_tree=False, force_update=False): """ show tree list :param has_tree: tree exist or not, False by default, if True, tree should be cleared first :param force_update: force update flag, if True, update neglect other flags. :return: has_tree, True successful, not ch...
python
{ "resource": "" }
q54778
MyAppFrame.show_data
train
def show_data(self, item): """ show data key-value in ListCtrl for tree item """ child, cookie = self.mainview_tree.GetFirstChild(item) child_list = [] while child.IsOk(): child_list.append(child) child, cookie = self.mainview_tree.GetNextChild(item, cooki...
python
{ "resource": "" }
q54779
MyAppFrame.json2lte
train
def json2lte(self, filename): """ convert json to lte return tuple of json, lte file content """ data_json = open(filename, 'r').read().strip() latins = lattice.Lattice(data_json) self.lattice_instance = latins self.all_beamlines = latins.getAllBl() ...
python
{ "resource": "" }
q54780
MyAppFrame.lte2json
train
def lte2json(self, filename): """ convert lte to json return tuple of json, lte file content """ lpins = lattice.LteParser(filename) data_json = lpins.file2json() latins = lattice.Lattice(lpins.file2json()) self.lattice_instance = latins self.all_bea...
python
{ "resource": "" }
q54781
MyAppFrame.get_refresh_flag
train
def get_refresh_flag(self, filename): """ set refresh data flag return True or False """ if filename is not None and filename != self.open_filename: self.open_filename = filename self.tree_refresh_flag = True self.data_refresh_flag = True ...
python
{ "resource": "" }
q54782
register_opts
train
def register_opts(conf): """Configure options within configuration library.""" conf.register_cli_opts(CLI_OPTS) conf.register_opts(EPISODE_OPTS) conf.register_opts(FORMAT_OPTS) conf.register_opts(CACHE_OPTS, 'cache')
python
{ "resource": "" }
q54783
list_opts
train
def list_opts(): """Returns a list of oslo_config options available in the library. The returned list includes all oslo_config options which may be registered at runtime by the library. Each element of the list is a tuple. The first element is the name of the group under which the list of elements ...
python
{ "resource": "" }
q54784
pick_inputs
train
def pick_inputs(workspace): """ Figure out which inputs don't yet have fragments. This is useful when some of your fragment generation jobs fail and you need to rerun them. """ frags_present = set() frags_absent = set() for path in workspace.input_paths: if workspace.fra...
python
{ "resource": "" }
q54785
get_files_in_dir
train
def get_files_in_dir(dir, *exts): """ Creates a list of files in a directory that have the provided extensions. :param dir: String path of directory containing files to be listed :param exts: Variable amount of string arguments specifying the extensions to be used. If none are provided, will de...
python
{ "resource": "" }
q54786
MyFrame.OnSelChanged
train
def OnSelChanged(self, event): """Method called when selected item is changed""" # Get the selected item object item = event.GetItem() obj = self.leftPanel.model.ItemToObject(item) if isinstance(obj, compass.Survey): l = [ 'Survey Name: %s' % obj.name,...
python
{ "resource": "" }
q54787
MyApp.OnInit
train
def OnInit(self): """Initialize by creating the split window with the tree""" project = compass.CompassProjectParser(sys.argv[1]).parse() frame = MyFrame(None, -1, 'wxCompass', project) frame.Show(True) self.SetTopWindow(frame) return True
python
{ "resource": "" }
q54788
hasattrs
train
def hasattrs(object, *names): """ Takes in an object and a variable length amount of named attributes, and checks to see if the object has each property. If any of the attributes are missing, this returns false. :param object: an object that may or may not contain the listed attributes :param n...
python
{ "resource": "" }
q54789
Proxy.call
train
def call(self, method, *args): """Perform a synchronous remote call where the returned value is given immediately. This may block for sometime in certain situations. If it takes more than the Proxies set timeout then a TimeoutError is raised. Any exceptions the remote call raised that ...
python
{ "resource": "" }
q54790
Proxy.response
train
def response(self, msgid, error, result): """Handle a results message given to the proxy by the protocol object.""" if error: self.requests[msgid].errback(Exception(str(error))) else: self.requests[msgid].callback(result) del self.requests[msgid]
python
{ "resource": "" }
q54791
init
train
def init(name, runtime): """Create a new Django app.""" runtime = click.unstyle(runtime) stdout.write( style.format_command( 'Initializing', '%s %s %s' % (name, style.gray('@'), style.green(runtime)) ) ) config = Config(os.getcwd()) config.set('runtime',...
python
{ "resource": "" }
q54792
check_coverage
train
def check_coverage(): """Checks if the coverage is 100%.""" with lcd(settings.LOCAL_COVERAGE_PATH): total_line = local('grep -n Total index.html', capture=True) match = re.search(r'^(\d+):', total_line) total_line_number = int(match.groups()[0]) percentage_line_number = total_lin...
python
{ "resource": "" }
q54793
create_db
train
def create_db(with_postgis=False): """ Creates the local database. :param with_postgis: If ``True``, the postgis extension will be installed. """ local_machine() local('psql {0} -c "CREATE USER {1} WITH PASSWORD \'{2}\'"'.format( USER_AND_HOST, env.db_role, DB_PASSWORD)) local('psq...
python
{ "resource": "" }
q54794
export_db
train
def export_db(filename=None, remote=False): """ Exports the database. Make sure that you have this in your ``~/.pgpass`` file: localhost:5433:*:<db_role>:<password> Also make sure that the file has ``chmod 0600 .pgpass``. Usage:: fab export_db fab export_db:filename=foobar.d...
python
{ "resource": "" }
q54795
drop_db
train
def drop_db(): """Drops the local database.""" local_machine() with fab_settings(warn_only=True): local('psql {0} -c "DROP DATABASE {1}"'.format( USER_AND_HOST, env.db_name)) local('psql {0} -c "DROP USER {1}"'.format( USER_AND_HOST, env.db_role))
python
{ "resource": "" }
q54796
jshint
train
def jshint(): """Runs jshint checks.""" with fab_settings(warn_only=True): needs_to_abort = False # because jshint fails with exit code 2, we need to allow this as # a successful exit code in our env if 2 not in env.ok_ret_codes: env.ok_ret_codes.append(2) out...
python
{ "resource": "" }
q54797
syntax_check
train
def syntax_check(): """Runs flake8 against the codebase.""" with fab_settings(warn_only=True): for file_type in settings.SYNTAX_CHECK: needs_to_abort = False # because egrep fails with exit code 1, we need to allow this as # a successful exit code in our env ...
python
{ "resource": "" }
q54798
import_db
train
def import_db(filename=None): """ Imports the database. Make sure that you have this in your ``~/.pgpass`` file: localhost:5433:*:publishizer_publishizer:publishizer Also make sure that the file has ``chmod 0600 .pgpass``. Usage:: fab import_db fab import_db:filename=foobar....
python
{ "resource": "" }
q54799
import_media
train
def import_media(filename=None): """ Extracts media dump into your local media root. Please note that this might overwrite existing local files. Usage:: fab import_media fab import_media:filename=foobar.tar.gz """ if not filename: filename = settings.MEDIA_DUMP_FILENA...
python
{ "resource": "" }