_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q261400
read_struct_array
validation
def read_struct_array(fd, endian, header): """Read a struct array. Returns a dict with fields of the struct array. """ # read field name length (unused, as strings are null terminated) field_name_length = read_elements(fd, endian, ['miINT32']) if field_name_length > 32: raise ParseError(...
python
{ "resource": "" }
q261401
eof
validation
def eof(fd): """Determine if end-of-file is reached for file fd.""" b = fd.read(1) end = len(b) == 0 if not end: curpos = fd.tell() fd.seek(curpos - 1) return end
python
{ "resource": "" }
q261402
write_elements
validation
def write_elements(fd, mtp, data, is_name=False): """Write data element tag and data. The tag contains the array type and the number of bytes the array data will occupy when written to file. If data occupies 4 bytes or less, it is written immediately as a Small Data Element (SDE). """ fmt ...
python
{ "resource": "" }
q261403
write_var_header
validation
def write_var_header(fd, header): """Write variable header""" # write tag bytes, # and array flags + class and nzmax (null bytes) fd.write(struct.pack('b3xI', etypes['miUINT32']['n'], 8)) fd.write(struct.pack('b3x4x', mclasses[header['mclass']])) # write dimensions array write_elements(fd,...
python
{ "resource": "" }
q261404
write_var_data
validation
def write_var_data(fd, data): """Write variable data to file""" # write array data elements (size info) fd.write(struct.pack('b3xI', etypes['miMATRIX']['n'], len(data))) # write the data fd.write(data)
python
{ "resource": "" }
q261405
write_compressed_var_array
validation
def write_compressed_var_array(fd, array, name): """Write compressed variable data to file""" bd = BytesIO() write_var_array(bd, array, name) data = zlib.compress(bd.getvalue()) bd.close() # write array data elements (size info) fd.write(struct.pack('b3xI', etypes['miCOMPRESSED']['n'], le...
python
{ "resource": "" }
q261406
write_numeric_array
validation
def write_numeric_array(fd, header, array): """Write the numeric array""" # make a memory file for writing array data bd = BytesIO() # write matrix header to memory file write_var_header(bd, header) if not isinstance(array, basestring) and header['dims'][0] > 1: # list array data in co...
python
{ "resource": "" }
q261407
isarray
validation
def isarray(array, test, dim=2): """Returns True if test is True for all array elements. Otherwise, returns False. """ if dim > 1: return all(isarray(array[i], test, dim - 1) for i in range(len(array))) return all(test(i) for i in array)
python
{ "resource": "" }
q261408
WebDriver._execute
validation
def _execute(self, command, data=None, unpack=True): """ Private method to execute command. Args: command(Command): The defined command. data(dict): The uri variable and body. uppack(bool): If unpack value from result. Returns: The unwrapped valu...
python
{ "resource": "" }
q261409
WebDriver.init
validation
def init(self): """Create Session by desiredCapabilities Support: Android iOS Web(WebView) Returns: WebDriver Object. """ resp = self._execute(Command.NEW_SESSION, { 'desiredCapabilities': self.desired_capabilities }, False) r...
python
{ "resource": "" }
q261410
WebDriver.switch_to_window
validation
def switch_to_window(self, window_name): """Switch to the given window. Support: Web(WebView) Args: window_name(str): The window to change focus to. Returns: WebDriver Object. """ data = { 'name': window_name } ...
python
{ "resource": "" }
q261411
WebDriver.set_window_size
validation
def set_window_size(self, width, height, window_handle='current'): """Sets the width and height of the current window. Support: Web(WebView) Args: width(int): the width in pixels. height(int): the height in pixels. window_handle(str): Identifier ...
python
{ "resource": "" }
q261412
WebDriver.set_window_position
validation
def set_window_position(self, x, y, window_handle='current'): """Sets the x,y position of the current window. Support: Web(WebView) Args: x(int): the x-coordinate in pixels. y(int): the y-coordinate in pixels. window_handle(str): Identifier of wi...
python
{ "resource": "" }
q261413
WebDriver.switch_to_frame
validation
def switch_to_frame(self, frame_reference=None): """Switches focus to the specified frame, by index, name, or webelement. Support: Web(WebView) Args: frame_reference(None|int|WebElement): The identifier of the frame to switch to. None mea...
python
{ "resource": "" }
q261414
WebDriver.execute_script
validation
def execute_script(self, script, *args): """Execute JavaScript Synchronously in current context. Support: Web(WebView) Args: script: The JavaScript to execute. *args: Arguments for your JavaScript. Returns: Returns the return value of th...
python
{ "resource": "" }
q261415
WebDriver.execute_async_script
validation
def execute_async_script(self, script, *args): """Execute JavaScript Asynchronously in current context. Support: Web(WebView) Args: script: The JavaScript to execute. *args: Arguments for your JavaScript. Returns: Returns the return valu...
python
{ "resource": "" }
q261416
WebDriver.add_cookie
validation
def add_cookie(self, cookie_dict): """Set a cookie. Support: Web(WebView) Args: cookie_dict: A dictionary contain keys: "name", "value", ["path"], ["domain"], ["secure"], ["httpOnly"], ["expiry"]. Returns: WebElement Object. ...
python
{ "resource": "" }
q261417
WebDriver.save_screenshot
validation
def save_screenshot(self, filename, quietly = False): """Save the screenshot to local. Support: Android iOS Web(WebView) Args: filename(str): The path to save the image. quietly(bool): If True, omit the IOError when failed to save the image. ...
python
{ "resource": "" }
q261418
WebDriver.element
validation
def element(self, using, value): """Find an element in the current context. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: WebElement Object. ...
python
{ "resource": "" }
q261419
WebDriver.elements
validation
def elements(self, using, value): """Find elements in the current context. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return a List<Element ...
python
{ "resource": "" }
q261420
WebDriver.wait_for
validation
def wait_for( self, timeout=10000, interval=1000, asserter=lambda x: x): """Wait for driver till satisfy the given condition Support: Android iOS Web(WebView) Args: timeout(int): How long we should be retrying stuff. interval(int): How long b...
python
{ "resource": "" }
q261421
WebDriver.wait_for_element
validation
def wait_for_element( self, using, value, timeout=10000, interval=1000, asserter=is_displayed): """Wait for element till satisfy the given condition Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str)...
python
{ "resource": "" }
q261422
WebDriver.wait_for_elements
validation
def wait_for_elements( self, using, value, timeout=10000, interval=1000, asserter=is_displayed): """Wait for elements till satisfy the given condition Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(st...
python
{ "resource": "" }
q261423
WebDriverResult.from_object
validation
def from_object(cls, obj): """The factory method to create WebDriverResult from JSON Object. Args: obj(dict): The JSON Object returned by server. """ return cls( obj.get('sessionId', None), obj.get('status', 0), obj.get('value', None) ...
python
{ "resource": "" }
q261424
WebDriverResult.raise_for_status
validation
def raise_for_status(self): """Raise WebDriverException if returned status is not zero.""" if not self.status: return error = find_exception_by_code(self.status) message = None screen = None stacktrace = None if isinstance(self.value, str): ...
python
{ "resource": "" }
q261425
fluent
validation
def fluent(func): """Fluent interface decorator to return self if method return None.""" @wraps(func) def fluent_interface(instance, *args, **kwargs): ret = func(instance, *args, **kwargs) if ret is not None: return ret return instance return fluent_interface
python
{ "resource": "" }
q261426
MemorizeFormatter.check_unused_args
validation
def check_unused_args(self, used_args, args, kwargs): """Implement the check_unused_args in superclass.""" for k, v in kwargs.items(): if k in used_args: self._used_kwargs.update({k: v}) else: self._unused_kwargs.update({k: v})
python
{ "resource": "" }
q261427
MemorizeFormatter.vformat
validation
def vformat(self, format_string, args, kwargs): """Clear used and unused dicts before each formatting.""" self._used_kwargs = {} self._unused_kwargs = {} return super(MemorizeFormatter, self).vformat(format_string, args, kwargs)
python
{ "resource": "" }
q261428
MemorizeFormatter.format_map
validation
def format_map(self, format_string, mapping): """format a string by a map Args: format_string(str): A format string mapping(dict): A map to format the string Returns: A formatted string. Raises: KeyError: if key is not provided by the gi...
python
{ "resource": "" }
q261429
find_exception_by_code
validation
def find_exception_by_code(code): """Find name of exception by WebDriver defined error code. Args: code(str): Error code defined in protocol. Returns: The error name defined in protocol. """ errorName = None for error in WebDriverError: if error.value.code == code: ...
python
{ "resource": "" }
q261430
RemoteInvoker.execute
validation
def execute(self, command, data={}): """Format the endpoint url by data and then request the remote server. Args: command(Command): WebDriver command to be executed. data(dict): Data fulfill the uri template and json body. Returns: A dict represent the json ...
python
{ "resource": "" }
q261431
RemoteInvoker._request
validation
def _request(self, method, url, body): """Internal method to send request to the remote server. Args: method(str): HTTP Method(GET/POST/PUT/DELET/HEAD). url(str): The request url. body(dict): The JSON object to be sent. Returns: A dict represent ...
python
{ "resource": "" }
q261432
WebElement._execute
validation
def _execute(self, command, data=None, unpack=True): """Private method to execute command with data. Args: command(Command): The defined command. data(dict): The uri variable and body. Returns: The unwrapped value field in the json response. """ ...
python
{ "resource": "" }
q261433
WebElement.element
validation
def element(self, using, value): """find an element in the current element. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: WebElement Object. ...
python
{ "resource": "" }
q261434
WebElement.element_or_none
validation
def element_or_none(self, using, value): """Check if an element in the current element. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return El...
python
{ "resource": "" }
q261435
WebElement.elements
validation
def elements(self, using, value): """find elements in the current element. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return a List<Element ...
python
{ "resource": "" }
q261436
is_displayed
validation
def is_displayed(target): """Assert whether the target is displayed Args: target(WebElement): WebElement Object. Returns: Return True if the element is displayed or return False otherwise. """ is_displayed = getattr(target, 'is_displayed', None) if not is_displayed or not calla...
python
{ "resource": "" }
q261437
vController.PlugIn
validation
def PlugIn(self): """Take next available controller id and plug in to Virtual USB Bus""" ids = self.available_ids() if len(ids) == 0: raise MaxInputsReachedError('Max Inputs Reached') self.id = ids[0] _xinput.PlugIn(self.id) while self.id in self.available_i...
python
{ "resource": "" }
q261438
vController.UnPlug
validation
def UnPlug(self, force=False): """Unplug controller from Virtual USB Bus and free up ID""" if force: _xinput.UnPlugForce(c_uint(self.id)) else: _xinput.UnPlug(c_uint(self.id)) while self.id not in self.available_ids(): if self.id == 0: ...
python
{ "resource": "" }
q261439
vController.set_value
validation
def set_value(self, control, value=None): """Set a value on the controller If percent is True all controls will accept a value between -1.0 and 1.0 If not then: Triggers are 0 to 255 Axis are -32768 to 32767 Control List: AxisLx , Left Stick X-Axis AxisLy ...
python
{ "resource": "" }
q261440
main
validation
def main(): """Test the functionality of the rController object""" import time print('Testing controller in position 1:') print('Running 3 x 3 seconds tests') # Initialise Controller con = rController(1) # Loop printing controller state and buttons held for i in range(3): prin...
python
{ "resource": "" }
q261441
rController.gamepad
validation
def gamepad(self): """Returns the current gamepad state. Buttons pressed is shown as a raw integer value. Use rController.buttons for a list of buttons pressed. """ state = _xinput_state() _xinput.XInputGetState(self.ControllerID - 1, pointer(state)) self.dwPacketNumber =...
python
{ "resource": "" }
q261442
rController.buttons
validation
def buttons(self): """Returns a list of buttons currently pressed""" return [name for name, value in rController._buttons.items() if self.gamepad.wButtons & value == value]
python
{ "resource": "" }
q261443
maybe_decode_header
validation
def maybe_decode_header(header): """ Decodes an encoded 7-bit ASCII header value into it's actual value. """ value, encoding = decode_header(header)[0] if encoding: return value.decode(encoding) else: return value
python
{ "resource": "" }
q261444
autodiscover
validation
def autodiscover(): """ Imports all available previews classes. """ from django.conf import settings for application in settings.INSTALLED_APPS: module = import_module(application) if module_has_submodule(module, 'emails'): emails = import_module('%s.emails' % applicatio...
python
{ "resource": "" }
q261445
PreviewSite.register
validation
def register(self, cls): """ Adds a preview to the index. """ preview = cls(site=self) logger.debug('Registering %r with %r', preview, self) index = self.__previews.setdefault(preview.module, {}) index[cls.__name__] = preview
python
{ "resource": "" }
q261446
PreviewSite.detail_view
validation
def detail_view(self, request, module, preview): """ Looks up a preview in the index, returning a detail view response. """ try: preview = self.__previews[module][preview] except KeyError: raise Http404 # The provided module/preview does not exist in the ...
python
{ "resource": "" }
q261447
Preview.url
validation
def url(self): """ The URL to access this preview. """ return reverse('%s:detail' % URL_NAMESPACE, kwargs={ 'module': self.module, 'preview': type(self).__name__, })
python
{ "resource": "" }
q261448
Preview.detail_view
validation
def detail_view(self, request): """ Renders the message view to a response. """ context = { 'preview': self, } kwargs = {} if self.form_class: if request.GET: form = self.form_class(data=request.GET) else: ...
python
{ "resource": "" }
q261449
split_docstring
validation
def split_docstring(value): """ Splits the docstring of the given value into it's summary and body. :returns: a 2-tuple of the format ``(summary, body)`` """ docstring = textwrap.dedent(getattr(value, '__doc__', '')) if not docstring: return None pieces = docstring.strip().split('\...
python
{ "resource": "" }
q261450
EmailMessageView.render_to_message
validation
def render_to_message(self, extra_context=None, **kwargs): """ Renders and returns an unsent message with the provided context. Any extra keyword arguments passed will be passed through as keyword arguments to the message constructor. :param extra_context: Any additional contex...
python
{ "resource": "" }
q261451
EmailMessageView.send
validation
def send(self, extra_context=None, **kwargs): """ Renders and sends an email message. All keyword arguments other than ``extra_context`` are passed through as keyword arguments when constructing a new :attr:`message_class` instance for this message. This method exists p...
python
{ "resource": "" }
q261452
TemplatedEmailMessageView.render_subject
validation
def render_subject(self, context): """ Renders the message subject for the given context. The context data is automatically unescaped to avoid rendering HTML entities in ``text/plain`` content. :param context: The context to use when rendering the subject template. :typ...
python
{ "resource": "" }
q261453
TemplatedHTMLEmailMessageView.render_to_message
validation
def render_to_message(self, extra_context=None, *args, **kwargs): """ Renders and returns an unsent message with the given context. Any extra keyword arguments passed will be passed through as keyword arguments to the message constructor. :param extra_context: Any additional co...
python
{ "resource": "" }
q261454
numeric
validation
def numeric(_, n): """ NBASE = 1000 ndigits = total number of base-NBASE digits weight = base-NBASE weight of first digit sign = 0x0000 if positive, 0x4000 if negative, 0xC000 if nan dscale = decimal digits after decimal place """ try: nt = n.as_tuple() except AttributeError:...
python
{ "resource": "" }
q261455
execute_from_command_line
validation
def execute_from_command_line(argv=None): """ A simple method that runs a ManagementUtility. """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--monitors-dir', default=MONITORS_DIR) parser.add_argument('--alerts-dir', default=ALERTS_DIR) parser.add_argument('--co...
python
{ "resource": "" }
q261456
_getCallingContext
validation
def _getCallingContext(): """ Utility function for the RedisLogRecord. Returns the module, function, and lineno of the function that called the logger. We look way up in the stack. The stack at this point is: [0] logger.py _getCallingContext (hey, that's me!) [1] logger.py __init__ ...
python
{ "resource": "" }
q261457
RedisFormatter.format
validation
def format(self, record): """ JSON-encode a record for serializing through redis. Convert date to iso format, and stringify any exceptions. """ data = record._raw.copy() # serialize the datetime date as utc string data['time'] = data['time'].isoformat() ...
python
{ "resource": "" }
q261458
RedisHandler.emit
validation
def emit(self, record): """ Publish record to redis logging channel """ try: self.redis_client.publish(self.channel, self.format(record)) except redis.RedisError: pass
python
{ "resource": "" }
q261459
RedisListHandler.emit
validation
def emit(self, record): """ Publish record to redis logging list """ try: if self.max_messages: p = self.redis_client.pipeline() p.rpush(self.key, self.format(record)) p.ltrim(self.key, -self.max_messages, -1) p....
python
{ "resource": "" }
q261460
require_template_debug
validation
def require_template_debug(f): """Decorated function is a no-op if TEMPLATE_DEBUG is False""" def _(*args, **kwargs): TEMPLATE_DEBUG = getattr(settings, 'TEMPLATE_DEBUG', False) return f(*args, **kwargs) if TEMPLATE_DEBUG else '' return _
python
{ "resource": "" }
q261461
_display_details
validation
def _display_details(var_data): """ Given a dictionary of variable attribute data from get_details display the data in the terminal. """ meta_keys = (key for key in list(var_data.keys()) if key.startswith('META_')) for key in meta_keys: display_key = key[5:].capitalize()...
python
{ "resource": "" }
q261462
set_trace
validation
def set_trace(context): """ Start a pdb set_trace inside of the template with the context available as 'context'. Uses ipdb if available. """ try: import ipdb as pdb except ImportError: import pdb print("For best results, pip install ipdb.") print("Variables that are ...
python
{ "resource": "" }
q261463
pydevd
validation
def pydevd(context): """ Start a pydev settrace """ global pdevd_not_available if pdevd_not_available: return '' try: import pydevd except ImportError: pdevd_not_available = True return '' render = lambda s: template.Template(s).render(context) availab...
python
{ "resource": "" }
q261464
_flatten
validation
def _flatten(iterable): """ Given an iterable with nested iterables, generate a flat iterable """ for i in iterable: if isinstance(i, Iterable) and not isinstance(i, string_types): for sub_i in _flatten(i): yield sub_i else: yield i
python
{ "resource": "" }
q261465
_get_detail_value
validation
def _get_detail_value(var, attr): """ Given a variable and one of its attributes that are available inside of a template, return its 'method' if it is a callable, its class name if it is a model manager, otherwise return its value """ value = getattr(var, attr) # Rename common Django class n...
python
{ "resource": "" }
q261466
get_attributes
validation
def get_attributes(var): """ Given a varaible, return the list of attributes that are available inside of a template """ is_valid = partial(is_valid_in_template, var) return list(filter(is_valid, dir(var)))
python
{ "resource": "" }
q261467
is_valid_in_template
validation
def is_valid_in_template(var, attr): """ Given a variable and one of its attributes, determine if the attribute is accessible inside of a Django template and return True or False accordingly """ # Remove private variables or methods if attr.startswith('_'): return False # Remove any ...
python
{ "resource": "" }
q261468
GitVcs.parse_log_messages
validation
def parse_log_messages(self, text): """Will parse git log messages in the 'short' format""" regex = r"commit ([0-9a-f]+)\nAuthor: (.*?)\n\n(.*?)(?:\n\n|$)" messages = re.findall(regex, text, re.DOTALL) parsed = [] for commit, author, message in messages: pars...
python
{ "resource": "" }
q261469
Command.determine_paths
validation
def determine_paths(self, package_name=None, create_package_dir=False, dry_run=False): """Determine paths automatically and a little intelligently""" # Give preference to the environment variable here as it will not # derefrence sym links self.project_dir = Path(os.getenv('PWD'...
python
{ "resource": "" }
q261470
check_integrity
validation
def check_integrity(sakefile, settings): """ Checks the format of the sakefile dictionary to ensure it conforms to specification Args: A dictionary that is the parsed Sakefile (from sake.py) The setting dictionary (for print functions) Returns: True if the Sakefile is confor...
python
{ "resource": "" }
q261471
check_shastore_version
validation
def check_shastore_version(from_store, settings): """ This function gives us the option to emit errors or warnings after sake upgrades """ sprint = settings["sprint"] error = settings["error"] sprint("checking .shastore version for potential incompatibilities", level="verbose") ...
python
{ "resource": "" }
q261472
get_sha
validation
def get_sha(a_file, settings=None): """ Returns sha1 hash of the file supplied as an argument """ if settings: error = settings["error"] else: error = ERROR_FN try: BLOCKSIZE = 65536 hasher = hashlib.sha1() with io.open(a_file, "rb") as fh: buf...
python
{ "resource": "" }
q261473
write_shas_to_shastore
validation
def write_shas_to_shastore(sha_dict): """ Writes a sha1 dictionary stored in memory to the .shastore file """ if sys.version_info[0] < 3: fn_open = open else: fn_open = io.open with fn_open(".shastore", "w") as fh: fh.write("---\n") fh.write('sake version: {}\...
python
{ "resource": "" }
q261474
take_shas_of_all_files
validation
def take_shas_of_all_files(G, settings): """ Takes sha1 hash of all dependencies and outputs of all targets Args: The graph we are going to build The settings dictionary Returns: A dictionary where the keys are the filenames and the value is the sha1 hash """ gl...
python
{ "resource": "" }
q261475
run_commands
validation
def run_commands(commands, settings): """ Runs the commands supplied as an argument It will exit the program if the commands return a non-zero code Args: the commands to run The settings dictionary """ sprint = settings["sprint"] quiet = settings["quiet"] error = set...
python
{ "resource": "" }
q261476
get_the_node_dict
validation
def get_the_node_dict(G, name): """ Helper function that returns the node data of the node with the name supplied """ for node in G.nodes(data=True): if node[0] == name: return node[1]
python
{ "resource": "" }
q261477
get_direct_ancestors
validation
def get_direct_ancestors(G, list_of_nodes): """ Returns a list of nodes that are the parents from all of the nodes given as an argument. This is for use in the parallel topo sort """ parents = [] for item in list_of_nodes: anc = G.predecessors(item) for one in anc: ...
python
{ "resource": "" }
q261478
get_sinks
validation
def get_sinks(G): """ A sink is a node with no children. This means that this is the end of the line, and it should be run last in topo sort. This returns a list of all sinks in a graph """ sinks = [] for node in G: if not len(list(G.successors(node))): sinks.append(n...
python
{ "resource": "" }
q261479
get_levels
validation
def get_levels(G): """ For the parallel topo sort to work, the targets have to be executed in layers such that there is no dependency relationship between any nodes in a layer. What is returned is a list of lists representing all the layers, or levels """ levels = [] ends = get_sinks...
python
{ "resource": "" }
q261480
merge_from_store_and_in_mems
validation
def merge_from_store_and_in_mems(from_store, in_mem_shas, dont_update_shas_of): """ If we don't merge the shas from the sha store and if we build a subgraph, the .shastore will only contain the shas of the files from the subgraph and the rest of the graph will have to be rebuilt """ if not f...
python
{ "resource": "" }
q261481
find_standard_sakefile
validation
def find_standard_sakefile(settings): """Returns the filename of the appropriate sakefile""" error = settings["error"] if settings["customsake"]: custom = settings["customsake"] if not os.path.isfile(custom): error("Specified sakefile '{}' doesn't exist", custom) sys....
python
{ "resource": "" }
q261482
get_ties
validation
def get_ties(G): """ If you specify a target that shares a dependency with another target, both targets need to be updated. This is because running one will resolve the sha mismatch and sake will think that the other one doesn't have to run. This is called a "tie". This function will find such ties....
python
{ "resource": "" }
q261483
get_tied_targets
validation
def get_tied_targets(original_targets, the_ties): """ This function gets called when a target is specified to ensure that all 'tied' targets also get included in the subgraph to be built """ my_ties = [] for original_target in original_targets: for item in the_ties: if or...
python
{ "resource": "" }
q261484
construct_graph
validation
def construct_graph(sakefile, settings): """ Takes the sakefile dictionary and builds a NetworkX graph Args: A dictionary that is the parsed Sakefile (from sake.py) The settings dictionary Returns: A NetworkX graph """ verbose = settings["verbose"] sprint = settings...
python
{ "resource": "" }
q261485
clean_all
validation
def clean_all(G, settings): """ Removes all the output files from all targets. Takes the graph as the only argument Args: The networkx graph object The settings dictionary Returns: 0 if successful 1 if removing even one file failed """ quiet = settings["quie...
python
{ "resource": "" }
q261486
write_dot_file
validation
def write_dot_file(G, filename): """ Writes the graph G in dot file format for graphviz visualization. Args: a Networkx graph A filename to name the dot files """ with io.open(filename, "w") as fh: fh.write("strict digraph DependencyDiagram {\n") edge_list = G.edges(...
python
{ "resource": "" }
q261487
itertable
validation
def itertable(table): """Auxiliary function for iterating over a data table.""" for item in table: res = { k.lower(): nfd(v) if isinstance(v, text_type) else v for k, v in item.items()} for extra in res.pop('extra', []): k, _, v = extra.partition(':') res[k.st...
python
{ "resource": "" }
q261488
_make_package
validation
def _make_package(args): # pragma: no cover """Prepare transcriptiondata from the transcription sources.""" from lingpy.sequence.sound_classes import token2class from lingpy.data import Model columns = ['LATEX', 'FEATURES', 'SOUND', 'IMAGE', 'COUNT', 'NOTE'] bipa = TranscriptionSystem('bipa') ...
python
{ "resource": "" }
q261489
is_valid_sound
validation
def is_valid_sound(sound, ts): """Check the consistency of a given transcription system conversino""" if isinstance(sound, (Marker, UnknownSound)): return False s1 = ts[sound.name] s2 = ts[sound.s] return s1.name == s2.name and s1.s == s2.s
python
{ "resource": "" }
q261490
TranscriptionSystem.normalize
validation
def normalize(self, string): """Normalize the string according to normalization list""" return ''.join([self._normalize.get(x, x) for x in nfd(string)])
python
{ "resource": "" }
q261491
TranscriptionSystem._from_name
validation
def _from_name(self, string): """Parse a sound from its name""" components = string.split(' ') if frozenset(components) in self.features: return self.features[frozenset(components)] rest, sound_class = components[:-1], components[-1] if sound_class in ['diphthong', 'c...
python
{ "resource": "" }
q261492
ipfn.iteration
validation
def iteration(self): """ Runs the ipfn algorithm. Automatically detects of working with numpy ndarray or pandas dataframes. """ i = 0 conv = np.inf old_conv = -np.inf conv_list = [] m = self.original # If the original data input is in pandas Data...
python
{ "resource": "" }
q261493
Accessor.resolve
validation
def resolve(self, context, quiet=True): """ Return an object described by the accessor by traversing the attributes of context. """ try: obj = context for level in self.levels: if isinstance(obj, dict): obj = ...
python
{ "resource": "" }
q261494
InlineMonthsColumn.get_days_span
validation
def get_days_span(self, month_index): """ Calculate how many days the month spans. """ is_first_month = month_index == 0 is_last_month = month_index == self.__len__() - 1 y = int(self.start_date.year + (self.start_date.month + month_index) / 13) m = int((self.sta...
python
{ "resource": "" }
q261495
_OPC._calculate_float
validation
def _calculate_float(self, byte_array): """Returns an IEEE 754 float from an array of 4 bytes :param byte_array: Expects an array of 4 bytes :type byte_array: array :rtype: float """ if len(byte_array) != 4: return None return struct.unpack('f', st...
python
{ "resource": "" }
q261496
_OPC._calculate_period
validation
def _calculate_period(self, vals): ''' calculate the sampling period in seconds ''' if len(vals) < 4: return None if self.firmware['major'] < 16: return ((vals[3] << 24) | (vals[2] << 16) | (vals[1] << 8) | vals[0]) / 12e6 else: return self._calculate...
python
{ "resource": "" }
q261497
_OPC.calculate_bin_boundary
validation
def calculate_bin_boundary(self, bb): """Calculate the adc value that corresponds to a specific bin boundary diameter in microns. :param bb: Bin Boundary in microns :type bb: float :rtype: int """ return min(enumerate(OPC_LOOKUP), key = lambda x: abs(x[1] ...
python
{ "resource": "" }
q261498
_OPC.read_info_string
validation
def read_info_string(self): """Reads the information string for the OPC :rtype: string :Example: >>> alpha.read_info_string() 'OPC-N2 FirmwareVer=OPC-018.2....................BD' """ infostring = [] # Send the command byte and sleep for 9 ms se...
python
{ "resource": "" }
q261499
_OPC.ping
validation
def ping(self): """Checks the connection between the Raspberry Pi and the OPC :rtype: Boolean """ b = self.cnxn.xfer([0xCF])[0] # send the command byte sleep(0.1) return True if b == 0xF3 else False
python
{ "resource": "" }