_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q36900
get_default_shell
train
def get_default_shell(): """ return the path to the default shell for the current user. """ if is_windows(): return 'cmd.exe' else: import pwd import getpass if 'SHELL' in os.environ: return os.environ['SHELL'] else: username = getpass...
python
{ "resource": "" }
q36901
_confirm_or_prompt_or_command
train
def _confirm_or_prompt_or_command(pymux): " True when we are waiting for a command, prompt or confirmation. " client_state = pymux.get_client_state() if client_state.confirm_text or client_state.prompt_command or client_state.command_mode: return True
python
{ "resource": "" }
q36902
BaseModel.mutate
train
def mutate(self): ''' Mutate to next state :return: True if mutated, False if not ''' self._get_ready() if self._is_last_index(): return False self._current_index += 1 self._mutate() return True
python
{ "resource": "" }
q36903
KittyWebClientApi.get_stats
train
def get_stats(self): ''' Get kitty stats as a dictionary ''' resp = requests.get('%s/api/stats.json' % self.url) assert(resp.status_code == 200) return resp.json()
python
{ "resource": "" }
q36904
BaseFuzzer._handle_options
train
def _handle_options(self, option_line): ''' Handle options from command line, in docopt style. This allows passing arguments to the fuzzer from the command line without the need to re-write it in each runner. :param option_line: string with the command line options to be parsed....
python
{ "resource": "" }
q36905
BaseFuzzer.set_model
train
def set_model(self, model): ''' Set the model to fuzz :type model: :class:`~kitty.model.high_level.base.BaseModel` or a subclass :param model: Model object to fuzz ''' self.model = model if self.model: self.model.set_notification_handler(self) ...
python
{ "resource": "" }
q36906
BaseFuzzer.set_range
train
def set_range(self, start_index=0, end_index=None): ''' Set range of tests to run .. deprecated:: use :func:`~kitty.fuzzers.base.BaseFuzzer.set_test_list` :param start_index: index to start at (default=0) :param end_index: index to end at(default=None) ''' ...
python
{ "resource": "" }
q36907
BaseFuzzer.start
train
def start(self): ''' Start the fuzzing session If fuzzer already running, it will return immediatly ''' if self._started: self.logger.warning('called while fuzzer is running. ignoring.') return self._started = True assert(self.model) ...
python
{ "resource": "" }
q36908
BaseFuzzer.handle_stage_changed
train
def handle_stage_changed(self, model): ''' handle a stage change in the data model :param model: the data model that was changed ''' stages = model.get_stages() if self.dataman: self.dataman.set('stages', stages)
python
{ "resource": "" }
q36909
BaseFuzzer.stop
train
def stop(self): ''' stop the fuzzing session ''' assert(self.model) assert(self.user_interface) assert(self.target) self.user_interface.stop() self.target.teardown() self.dataman.submit_task(None) self._un_set_signal_handler()
python
{ "resource": "" }
q36910
BaseFuzzer._keep_running
train
def _keep_running(self): ''' Should we still fuzz?? ''' if self.config.max_failures: if self.session_info.failure_count >= self.config.max_failures: return False return self._test_list.current() is not None
python
{ "resource": "" }
q36911
KittyObject.set_verbosity
train
def set_verbosity(cls, verbosity): ''' Set verbosity of logger :param verbosity: verbosity level. currently, we only support 1 (logging.DEBUG) ''' if verbosity > 0: # currently, we only toggle between INFO, DEBUG logger = KittyObject.get_logger() ...
python
{ "resource": "" }
q36912
KittyObject.not_implemented
train
def not_implemented(self, func_name): ''' log access to unimplemented method and raise error :param func_name: name of unimplemented function. :raise: NotImplementedError detailing the function the is not implemented. ''' msg = '%s is not overridden by %s' % (func_name, ...
python
{ "resource": "" }
q36913
synced
train
def synced(func): ''' Decorator for functions that should be called synchronously from another thread :param func: function to call ''' def wrapper(self, *args, **kwargs): ''' Actual wrapper for the synchronous function ''' task = DataManagerTask(func, *args, **kwar...
python
{ "resource": "" }
q36914
DataManagerTask.execute
train
def execute(self, dataman): ''' run the task :type dataman: :class:`~kitty.data.data_manager.DataManager` :param dataman: the executing data manager ''' self._event.clear() try: self._result = self._task(dataman, *self._args) # # We ar...
python
{ "resource": "" }
q36915
DataManager.open
train
def open(self): ''' open the database ''' self._connection = sqlite3.connect(self._dbname) self._cursor = self._connection.cursor() self._session_info = SessionInfoTable(self._connection, self._cursor) self._reports = ReportsTable(self._connection, self._cursor)
python
{ "resource": "" }
q36916
DataManager.set
train
def set(self, key, data): ''' set arbitrary data by key in volatile memory :param key: key of the data :param data: data to be stored ''' if isinstance(data, dict): self._volatile_data[key] = {k: v for (k, v) in data.items()} else: self._v...
python
{ "resource": "" }
q36917
Table.row_to_dict
train
def row_to_dict(self, row): ''' translate a row of the current table to dictionary :param row: a row of the current table (selected with \\*) :return: dictionary of all fields ''' res = {} for i in range(len(self._fields)): res[self._fields[i][0]] = r...
python
{ "resource": "" }
q36918
MainGUI.register_palette
train
def register_palette(self): """Converts pygmets style to urwid palatte""" default = 'default' palette = list(self.palette) mapping = CONFIG['rgb_to_short'] for tok in self.style.styles.keys(): for t in tok.split()[::-1]: st = self.style.styles[t] ...
python
{ "resource": "" }
q36919
Permutations.increment
train
def increment(self): """ Increment the last permutation we returned to the next. """ # Increment position from the deepest place of the tree first. for index in reversed(range(self.depth)): self.indexes[index] += 1 # We haven't reached the end of board, no need to adjust ...
python
{ "resource": "" }
q36920
Permutations.skip_branch
train
def skip_branch(self, level): """ Abandon the branch at the provided level and skip to the next. When we call out to skip to the next branch of the search space, we push sublevel pieces to the maximum positions of the board. So that the next time the permutation iterator is called, it c...
python
{ "resource": "" }
q36921
SolverContext.solve
train
def solve(self): """ Solve all possible positions of pieces within the context. Depth-first, tree-traversal of the product space. """ # Create a new, empty board. board = Board(self.length, self.height) # Iterate through all combinations of positions. permutatio...
python
{ "resource": "" }
q36922
get_flagged_names
train
def get_flagged_names(): """Return a list of all filenames marked as flagged.""" l = [] for w in _widget_cache.values(): if w.flagged: l.append(w.get_node().get_value()) return l
python
{ "resource": "" }
q36923
starts_expanded
train
def starts_expanded(name): """Return True if directory is a parent of initial cwd.""" if name is '/': return True l = name.split(dir_sep()) if len(l) > len(_initial_cwd): return False if l != _initial_cwd[:len(l)]: return False return True
python
{ "resource": "" }
q36924
escape_filename_sh
train
def escape_filename_sh(name): """Return a hopefully safe shell-escaped version of a filename.""" # check whether we have unprintable characters for ch in name: if ord(ch) < 32: # found one so use the ansi-c escaping return escape_filename_sh_ansic(name) # all printable ...
python
{ "resource": "" }
q36925
escape_filename_sh_ansic
train
def escape_filename_sh_ansic(name): """Return an ansi-c shell-escaped version of a filename.""" out =[] # gather the escaped characters into a list for ch in name: if ord(ch) < 32: out.append("\\x%02x"% ord(ch)) elif ch == '\\': out.append('\\\\') else: ...
python
{ "resource": "" }
q36926
FlagFileWidget.keypress
train
def keypress(self, size, key): """allow subclasses to intercept keystrokes""" key = self.__super.keypress(size, key) if key: key = self.unhandled_keys(size, key) return key
python
{ "resource": "" }
q36927
FlagFileWidget.update_w
train
def update_w(self): """Update the attributes of self.widget based on self.flagged. """ if self.flagged: self._w.attr = 'flagged' self._w.focus_attr = 'flagged focus' else: self._w.attr = 'body' self._w.focus_attr = 'focus'
python
{ "resource": "" }
q36928
DirectoryNode.load_child_node
train
def load_child_node(self, key): """Return either a FileNode or DirectoryNode""" index = self.get_child_index(key) if key is None: return EmptyNode(None) else: path = os.path.join(self.get_value(), key) if index < self.dir_count: return ...
python
{ "resource": "" }
q36929
PasswordForm.clean_password
train
def clean_password(self): """ Validates that the password is a current password """ user_pass = self.cleaned_data.get('password') matches = Password.objects.filter(password=user_pass) if not matches: raise forms.ValidationError("Your password does not match.")
python
{ "resource": "" }
q36930
gfm
train
def gfm(text): """Processes Markdown according to GitHub Flavored Markdown spec.""" extractions = {} def extract_pre_block(matchobj): match = matchobj.group(0) hashed_match = hashlib.md5(match.encode('utf-8')).hexdigest() extractions[hashed_match] = match result = "{gfm-extr...
python
{ "resource": "" }
q36931
markdown
train
def markdown(text): """Processes GFM then converts it to HTML.""" text = gfm(text) text = markdown_lib.markdown(text) return text
python
{ "resource": "" }
q36932
Command.add_log_options
train
def add_log_options(self, verbose_func=None, quiet_func=None): """ A helper for setting up log options """ if not verbose_func: def verbose_func(): return log.config(verbose=True) if not quiet_func: def quiet_func(): retur...
python
{ "resource": "" }
q36933
BGP.redistribute
train
def redistribute(self, **kwargs): """Set BGP redistribute properties. Args: vrf (str): The VRF for this BGP process. rbridge_id (str): The rbridge ID of the device on which BGP will be configured in a VCS fabric. source (str): Source for redistributin...
python
{ "resource": "" }
q36934
BGP._redistribute_builder
train
def _redistribute_builder(self, afi='ipv4', source=None): """Build BGP redistribute method. Do not use this method directly. You probably want ``redistribute``. Args: source (str): Source for redistributing. (connected) afi (str): Address family to configure. (ipv4, ip...
python
{ "resource": "" }
q36935
BGP.max_paths
train
def max_paths(self, **kwargs): """Set BGP max paths property. Args: vrf (str): The VRF for this BGP process. rbridge_id (str): The rbridge ID of the device on which BGP will be configured in a VCS fabric. paths (str): Number of paths for BGP ECMP (def...
python
{ "resource": "" }
q36936
BGP._multihop_xml
train
def _multihop_xml(self, **kwargs): """Build BGP multihop XML. Do not use this method directly. You probably want ``multihop``. Args: rbridge_id (str): The rbridge ID of the device on which BGP will be configured in a VCS fabric. neighbor (ipaddress.ip_i...
python
{ "resource": "" }
q36937
return_xml
train
def return_xml(element_tree): """Return an XML Element. Args: element_tree (Element): XML Element to be returned. If sent as a ``str``, this function will attempt to convert it to an ``Element``. Returns: Element: An XML Element. Ra...
python
{ "resource": "" }
q36938
valid_vlan_id
train
def valid_vlan_id(vlan_id, extended=True): """Validates a VLAN ID. Args: vlan_id (integer): VLAN ID to validate. If passed as ``str``, it will be cast to ``int``. extended (bool): If the VLAN ID range should be considered extended for Virtual Fabrics. Returns: ...
python
{ "resource": "" }
q36939
merge_xml
train
def merge_xml(first_doc, second_doc): """Merges two XML documents. Args: first_doc (str): First XML document. `second_doc` is merged into this document. second_doc (str): Second XML document. It is merged into the first. Returns: XML Document: The merged document. ...
python
{ "resource": "" }
q36940
FileSystemEvents.get_scss_files
train
def get_scss_files(self, skip_partials=True, with_source_path=False): """Gets all SCSS files in the source directory. :param bool skip_partials: If True, partials will be ignored. Otherwise, all SCSS files, including ones that begin ...
python
{ "resource": "" }
q36941
DatasetPostgreSQLIndex._index_document
train
def _index_document(self, document, force=False): """ Adds dataset document to the index. """ query = text(""" INSERT INTO dataset_index(vid, title, keywords, doc) VALUES(:vid, :title, string_to_array(:keywords, ' '), to_tsvector('english', :doc)); """) self.execu...
python
{ "resource": "" }
q36942
PartitionPostgreSQLIndex.is_indexed
train
def is_indexed(self, partition): """ Returns True if partition is already indexed. Otherwise returns False. """ query = text(""" SELECT vid FROM partition_index WHERE vid = :vid; """) result = self.execute(query, vid=partition.vid) return bool(...
python
{ "resource": "" }
q36943
IdentifierPostgreSQLIndex.search
train
def search(self, search_phrase, limit=None): """ Finds identifiers by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to return. None means without limit. Returns: list of IdentifierSearchResult instances. ...
python
{ "resource": "" }
q36944
pare
train
def pare(text, size, etc='...'): '''Pare text to have maximum size and add etc to the end if it's changed''' size = int(size) text = text.strip() if len(text)>size: # strip the last word or not to_be_stripped = not whitespace_re.findall(text[size-1:size+2]) text = text[:size...
python
{ "resource": "" }
q36945
get_environment
train
def get_environment(id=None, name=None): """ Get a specific Environment by name or ID """ data = get_environment_raw(id, name) if data: return utils.format_json(data)
python
{ "resource": "" }
q36946
list_environments_raw
train
def list_environments_raw(page_size=200, page_index=0, sort="", q=""): """ List all Environments """ response = utils.checked_api_call(pnc_api.environments, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q) if response: return response.content
python
{ "resource": "" }
q36947
Table.primary_dimensions
train
def primary_dimensions(self): """Iterate over the primary dimension columns, columns which do not have a parent """ from ambry.valuetype.core import ROLE for c in self.columns: if not c.parent and c.role == ROLE.DIMENSION: yield c
python
{ "resource": "" }
q36948
Table.primary_measures
train
def primary_measures(self): """Iterate over the primary columns, columns which do not have a parent Also sets the property partition_stats to the stats collection for the partition and column. """ from ambry.valuetype.core import ROLE for c in self.columns: if not ...
python
{ "resource": "" }
q36949
Table.is_empty
train
def is_empty(self): """Return True if the table has no columns or the only column is the id""" if len(self.columns) == 0: return True if len(self.columns) == 1 and self.columns[0].name == 'id': return True return False
python
{ "resource": "" }
q36950
Table.update_from_stats
train
def update_from_stats(self, stats): """Update columns based on partition statistics""" sd = dict(stats) for c in self.columns: if c not in sd: continue stat = sd[c] if stat.size and stat.size > c.size: c.size = stat.size ...
python
{ "resource": "" }
q36951
Table.transforms
train
def transforms(self): """Return an array of arrays of column transforms. #The return value is an list of list, with each list being a segment of column transformations, and #each segment having one entry per column. """ tr = [] for c in self.columns: tr.app...
python
{ "resource": "" }
q36952
Table.before_insert
train
def before_insert(mapper, conn, target): """event.listen method for Sqlalchemy to set the seqience_id for this object and create an ObjectNumber value for the id""" if target.sequence_id is None: from ambry.orm.exc import DatabaseError raise DatabaseError('Must have seque...
python
{ "resource": "" }
q36953
Table.before_update
train
def before_update(mapper, conn, target): """Set the Table ID based on the dataset number and the sequence number for the table.""" target.name = Table.mangle_name(target.name) if isinstance(target, Column): raise TypeError('Got a column instead of a table') target....
python
{ "resource": "" }
q36954
SessionManager.wait_for_tasks
train
def wait_for_tasks(self, raise_if_error=True): """ Wait for the running tasks lauched from the sessions. Note that it also wait for tasks that are started from other tasks callbacks, like on_finished. :param raise_if_error: if True, raise all possible encountered er...
python
{ "resource": "" }
q36955
CommandTask.error
train
def error(self): """ Return an instance of Exception if any, else None. Actually check for a :class:`TimeoutError` or a :class:`ExitCodeError`. """ if self.__timed_out: return TimeoutError(self.session, self, "timeout") if self.__exit_code is not None...
python
{ "resource": "" }
q36956
Dataset.incver
train
def incver(self): """Increment all of the version numbers""" d = {} for p in self.__mapper__.attrs: if p.key in ['vid','vname','fqname', 'version', 'cache_key']: continue if p.key == 'revision': d[p.key] = self.revision + 1 else...
python
{ "resource": "" }
q36957
Dataset.new_unique_object
train
def new_unique_object(self, table_class, sequence_id=None, force_query=False, **kwargs): """Use next_sequence_id to create a new child of the dataset, with a unique id""" from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import FlushError # If a sequence ID was specified...
python
{ "resource": "" }
q36958
Dataset.new_table
train
def new_table(self, name, add_id=True, **kwargs): '''Add a table to the schema, or update it it already exists. If updating, will only update data. ''' from . import Table from .exc import NotFoundError try: table = self.table(name) extant = True...
python
{ "resource": "" }
q36959
Dataset.new_partition
train
def new_partition(self, table, **kwargs): """ Creates new partition and returns it. Args: table (orm.Table): Returns: orm.Partition """ from . import Partition # Create the basic partition record, with a sequence ID. if isinstance(tabl...
python
{ "resource": "" }
q36960
Dataset.partition
train
def partition(self, ref=None, **kwargs): """ Returns partition by ref. """ from .exc import NotFoundError from six import text_type if ref: for p in self.partitions: # This is slow for large datasets, like Census years. if (text_type(ref) == text_type(p.name...
python
{ "resource": "" }
q36961
Dataset.bsfile
train
def bsfile(self, path): """Return a Build Source file ref, creating a new one if the one requested does not exist""" from sqlalchemy.orm.exc import NoResultFound from ambry.orm.exc import NotFoundError try: f = object_session(self)\ .query(File)\ ...
python
{ "resource": "" }
q36962
Dataset.row
train
def row(self, fields): """Return a row for fields, for CSV files, pretty printing, etc, give a set of fields to return""" d = self.dict row = [None] * len(fields) for i, f in enumerate(fields): if f in d: row[i] = d[f] return row
python
{ "resource": "" }
q36963
ConfigAccessor.metadata
train
def metadata(self): """Access process configuarion values as attributes. """ from ambry.metadata.schema import Top # cross-module import top = Top() top.build_from_db(self.dataset) return top
python
{ "resource": "" }
q36964
ConfigAccessor.rows
train
def rows(self): """Return configuration in a form that can be used to reconstitute a Metadata object. Returns all of the rows for a dataset. This is distinct from get_config_value, which returns the value for the library. """ from ambry.orm import Config as SAConfig ...
python
{ "resource": "" }
q36965
_set_value
train
def _set_value(instance_to_path_map, path_to_instance_map, prop_tree, config_instance): """ Finds appropriate term in the prop_tree and sets its value from config_instance. Args: configs_map (dict): key is id of the config, value is Config instance (AKA cache of the configs) prop_tree (Property...
python
{ "resource": "" }
q36966
get_or_create
train
def get_or_create(session, model, **kwargs): """ Get or create sqlalchemy instance. Args: session (Sqlalchemy session): model (sqlalchemy model): kwargs (dict): kwargs to lookup or create instance. Returns: Tuple: first element is found or created instance, second is boolea...
python
{ "resource": "" }
q36967
_get_config_instance
train
def _get_config_instance(group_or_term, session, **kwargs): """ Finds appropriate config instance and returns it. Args: group_or_term (Group or Term): session (Sqlalchemy session): kwargs (dict): kwargs to pass to get_or_create. Returns: tuple of (Config, bool): """ ...
python
{ "resource": "" }
q36968
StructuredPropertyTree.register_members
train
def register_members(self): """Collect the names of the class member and convert them to object members. Unlike Terms, the Group class members are converted into object members, so the configuration data """ self._members = { name: attr for name, attr in it...
python
{ "resource": "" }
q36969
StructuredPropertyTree.add_error
train
def add_error(self, group, term, sub_term, value): """For records that are not defined as terms, either add it to the errors list.""" self._errors[(group, term, sub_term)] = value
python
{ "resource": "" }
q36970
StructuredPropertyTree._jinja_sub
train
def _jinja_sub(self, st): """Create a Jina template engine, then perform substitutions on a string""" if isinstance(st, string_types): from jinja2 import Template try: for i in range(5): # Only do 5 recursive substitutions. st = Template(st)...
python
{ "resource": "" }
q36971
StructuredPropertyTree.scalar_term
train
def scalar_term(self, st): """Return a _ScalarTermS or _ScalarTermU from a string, to perform text and HTML substitutions""" if isinstance(st, binary_type): return _ScalarTermS(st, self._jinja_sub) elif isinstance(st, text_type): return _ScalarTermU(st, self._jinja_sub) ...
python
{ "resource": "" }
q36972
Group.update_config
train
def update_config(self): """ Updates or creates config of that group. Requires tree bound to db. """ dataset = self._top._config.dataset session = object_session(self._top._config) logger.debug( 'Updating group config. dataset: {}, type: {}, key: {}'.format(dataset.vid, self....
python
{ "resource": "" }
q36973
Group.get_group_instance
train
def get_group_instance(self, parent): """Create an instance object""" o = copy.copy(self) o.init_instance(parent) return o
python
{ "resource": "" }
q36974
VarDictGroup.update_config
train
def update_config(self, key, value): """ Creates or updates db config of the VarDictGroup. Requires bound to db tree. """ dataset = self._top._config.dataset session = object_session(self._top._config) logger.debug( 'Updating VarDictGroup config. dataset: {}, type: {}, key: {...
python
{ "resource": "" }
q36975
Term.update_config
train
def update_config(self): """ Creates or updates db config of the term. Requires bound to db tree. """ dataset = self._top._config.dataset session = object_session(self._top._config) #logger.debug('Updating term config. dataset: {}, type: {}, key: {}, value: {}'.format( # ...
python
{ "resource": "" }
q36976
_ScalarTermS.text
train
def text(self): """Interpret the scalar as Markdown, strip the HTML and return text""" s = MLStripper() s.feed(self.html) return s.get_data()
python
{ "resource": "" }
q36977
quoteattrs
train
def quoteattrs(data): '''Takes dict of attributes and returns their HTML representation''' items = [] for key, value in data.items(): items.append('{}={}'.format(key, quoteattr(value))) return ' '.join(items)
python
{ "resource": "" }
q36978
quote_js
train
def quote_js(text): '''Quotes text to be used as JavaScript string in HTML templates. The result doesn't contain surrounding quotes.''' if isinstance(text, six.binary_type): text = text.decode('utf-8') # for Jinja2 Markup text = text.replace('\\', '\\\\'); text = text.replace('\n', '\\n'); ...
python
{ "resource": "" }
q36979
create_ramp_plan
train
def create_ramp_plan(err, ramp): """ Formulate and execute on a plan to slowly add heat or cooling to the system `err` initial error (PV - SP) `ramp` the size of the ramp A ramp plan might yield MVs in this order at every timestep: [5, 0, 4, 0, 3, 0, 2, 0, 1] where err == 5 + 4 + 3...
python
{ "resource": "" }
q36980
BaseField.clean_value
train
def clean_value(self): ''' Current field's converted value from form's python_data. ''' # XXX cached_property is used only for set initial state # this property should be set every time field data # has been changed, for instance, in accept method python_d...
python
{ "resource": "" }
q36981
Field.accept
train
def accept(self): '''Extracts raw value from form's raw data and passes it to converter''' value = self.raw_value if not self._check_value_type(value): # XXX should this be silent or TypeError? value = [] if self.multiple else self._null_value self.clean_value = s...
python
{ "resource": "" }
q36982
AggregateField.python_data
train
def python_data(self): '''Representation of aggregate value as dictionary.''' try: value = self.clean_value except LookupError: # XXX is this necessary? value = self.get_initial() return self.from_python(value)
python
{ "resource": "" }
q36983
FieldSet.accept
train
def accept(self): ''' Accepts all children fields, collects resulting values into dict and passes that dict to converter. Returns result of converter as separate value in parent `python_data` ''' result = dict(self.python_data) for field in self.fields: ...
python
{ "resource": "" }
q36984
FieldBlock.accept
train
def accept(self): ''' Acts as `Field.accepts` but returns result of every child field as value in parent `python_data`. ''' result = FieldSet.accept(self) self.clean_value = result[self.name] return self.clean_value
python
{ "resource": "" }
q36985
getTicker
train
def getTicker(pair, connection=None, info=None): """Retrieve the ticker for the given pair. Returns a Ticker instance.""" if info is not None: info.validate_pair(pair) if connection is None: connection = common.BTCEConnection() response = connection.makeJSONRequest("/api/3/ticker/%s"...
python
{ "resource": "" }
q36986
getTradeHistory
train
def getTradeHistory(pair, connection=None, info=None, count=None): """Retrieve the trade history for the given pair. Returns a list of Trade instances. If count is not None, it should be an integer, and specifies the number of items from the trade history that will be processed and returned.""" i...
python
{ "resource": "" }
q36987
BuildSourceFile.remove
train
def remove(self): """ Removes file from filesystem. """ from fs.errors import ResourceNotFoundError try: self._fs.remove(self.file_name) except ResourceNotFoundError: pass
python
{ "resource": "" }
q36988
BuildSourceFile.sync
train
def sync(self, force=None): """Synchronize between the file in the file system and the field record""" try: if force: sd = force else: sd = self.sync_dir() if sd == self.SYNC_DIR.FILE_TO_RECORD: if force and not self....
python
{ "resource": "" }
q36989
DictBuildSourceFile.record_to_fh
train
def record_to_fh(self, f): """Write the record, in filesystem format, to a file handle or file object""" fr = self.record if fr.contents: yaml.safe_dump(fr.unpacked_contents, f, default_flow_style=False, encoding='utf-8') fr.source_hash = self.fs_hash fr.mod...
python
{ "resource": "" }
q36990
MetadataFile.objects_to_record
train
def objects_to_record(self): """Write from object metadata to the record. Note that we don't write everything""" o = self.get_object() o.about = self._bundle.metadata.about o.identity = self._dataset.identity.ident_dict o.names = self._dataset.identity.names_dict o.cont...
python
{ "resource": "" }
q36991
MetadataFile.update_identity
train
def update_identity(self): """Update the identity and names to match the dataset id and version""" fr = self.record d = fr.unpacked_contents d['identity'] = self._dataset.identity.ident_dict d['names'] = self._dataset.identity.names_dict fr.update_contents(msgpack.pac...
python
{ "resource": "" }
q36992
MetadataFile.get_object
train
def get_object(self): """Return contents in object form, an AttrDict""" from ..util import AttrDict c = self.record.unpacked_contents if not c: c = yaml.safe_load(self.default) return AttrDict(c)
python
{ "resource": "" }
q36993
NotebookFile.execute
train
def execute(self): """Convert the notebook to a python script and execute it, returning the local context as a dict""" from nbformat import read from nbconvert.exporters import export_script from cStringIO import StringIO notebook = read(StringIO(self.record.unpacked_co...
python
{ "resource": "" }
q36994
PythonSourceFile.import_module
train
def import_module(self, module_path = 'ambry.build', **kwargs): """ Import the contents of the file into the ambry.build module :param kwargs: items to add to the module globals :return: """ from fs.errors import NoSysPathError if module_path in sys.modules: ...
python
{ "resource": "" }
q36995
PythonSourceFile.import_bundle
train
def import_bundle(self): """Add the filesystem to the Python sys path with an import hook, then import to file as Python""" from fs.errors import NoSysPathError try: import ambry.build module = sys.modules['ambry.build'] except ImportError: mo...
python
{ "resource": "" }
q36996
PythonSourceFile.import_lib
train
def import_lib(self): """Import the lib.py file into the bundle module""" try: import ambry.build module = sys.modules['ambry.build'] except ImportError: module = imp.new_module('ambry.build') sys.modules['ambry.build'] = module bf = self...
python
{ "resource": "" }
q36997
SourceSchemaFile.record_to_objects
train
def record_to_objects(self): """Write from the stored file data to the source records""" from ambry.orm import SourceTable bsfile = self.record failures = set() # Clear out all of the columns from existing tables. We don't clear out the # tables, since they may be refe...
python
{ "resource": "" }
q36998
ASQLSourceFile.execute
train
def execute(self): """ Executes all sql statements from bundle.sql. """ from ambry.mprlib import execute_sql execute_sql(self._bundle.library, self.record_content)
python
{ "resource": "" }
q36999
BuildSourceFileAccessor.list_records
train
def list_records(self, file_const=None): """Iterate through the file records""" for r in self._dataset.files: if file_const and r.minor_type != file_const: continue yield self.instance_from_name(r.path)
python
{ "resource": "" }