_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q265400
dmap
validation
def dmap(fn, record): """map for a directory""" values = (fn(v) for k, v in record.items()) return dict(itertools.izip(record, values))
python
{ "resource": "" }
q265401
apply_types
validation
def apply_types(use_types, guess_type, line): """Apply the types on the elements of the line""" new_line = {} for k, v in line.items(): if use_types.has_key(k): new_line[k] = force_type(use_types[k], v) elif guess_type: new_line[k] = determine_type(v) else: ...
python
{ "resource": "" }
q265402
format_to_csv
validation
def format_to_csv(filename, skiprows=0, delimiter=""): """Convert a file to a .csv file""" if not delimiter: delimiter = "\t" input_file = open(filename, "r") if skiprows: [input_file.readline() for _ in range(skiprows)] new_filename = os.path.splitext(filename)[0] + ".csv" o...
python
{ "resource": "" }
q265403
admin_obj_link
validation
def admin_obj_link(obj, display=''): """Returns a link to the django admin change list with a filter set to only the object given. :param obj: Object to create the admin change list display link for :param display: Text to display in the link. Defaults to string call of the object ...
python
{ "resource": "" }
q265404
_obj_display
validation
def _obj_display(obj, display=''): """Returns string representation of an object, either the default or based on the display template passed in. """ result = '' if not display: result = str(obj) else: template = Template(display) context = Context({'obj':obj}) res...
python
{ "resource": "" }
q265405
FancyModelAdmin.add_link
validation
def add_link(cls, attr, title='', display=''): """Adds a ``list_display`` attribute that appears as a link to the django admin change page for the type of object being shown. Supports double underscore attribute name dereferencing. :param attr: Name of the attribute to deref...
python
{ "resource": "" }
q265406
FancyModelAdmin.add_object
validation
def add_object(cls, attr, title='', display=''): """Adds a ``list_display`` attribute showing an object. Supports double underscore attribute name dereferencing. :param attr: Name of the attribute to dereference from the corresponding object, i.e. what will be lined to....
python
{ "resource": "" }
q265407
FancyModelAdmin.add_formatted_field
validation
def add_formatted_field(cls, field, format_string, title=''): """Adds a ``list_display`` attribute showing a field in the object using a python %formatted string. :param field: Name of the field in the object. :param format_string: A old-style (to remain python ...
python
{ "resource": "" }
q265408
post_required
validation
def post_required(method_or_options=[]): """View decorator that enforces that the method was called using POST. This decorator can be called with or without parameters. As it is expected to wrap a view, the first argument of the method being wrapped is expected to be a ``request`` object. .. code-...
python
{ "resource": "" }
q265409
json_post_required
validation
def json_post_required(*decorator_args): """View decorator that enforces that the method was called using POST and contains a field containing a JSON dictionary. This method should only be used to wrap views and assumes the first argument of the method being wrapped is a ``request`` object. .. code...
python
{ "resource": "" }
q265410
Match.sigma_prime
validation
def sigma_prime(self): """ Divergence of matched beam """ return _np.sqrt(self.emit/self.beta(self.E))
python
{ "resource": "" }
q265411
MatchPlasma.n_p
validation
def n_p(self): """ The plasma density in SI units. """ return 2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.beta*_spc.elementary_charge)**2
python
{ "resource": "" }
q265412
main
validation
def main(target, label): """ Semver tag triggered deployment helper """ check_environment(target, label) click.secho('Fetching tags from the upstream ...') handler = TagHandler(git.list_tags()) print_information(handler, label) tag = handler.yield_tag(target, label) confirm(tag)
python
{ "resource": "" }
q265413
check_environment
validation
def check_environment(target, label): """ Performs some environment checks prior to the program's execution """ if not git.exists(): click.secho('You must have git installed to use yld.', fg='red') sys.exit(1) if not os.path.isdir('.git'): click.secho('You must cd into a git...
python
{ "resource": "" }
q265414
print_information
validation
def print_information(handler, label): """ Prints latest tag's information """ click.echo('=> Latest stable: {tag}'.format( tag=click.style(str(handler.latest_stable or 'N/A'), fg='yellow' if handler.latest_stable else 'magenta') )) if label is not None: ...
python
{ "resource": "" }
q265415
confirm
validation
def confirm(tag): """ Prompts user before proceeding """ click.echo() if click.confirm('Do you want to create the tag {tag}?'.format( tag=click.style(str(tag), fg='yellow')), default=True, abort=True): git.create_tag(tag) if click.confirm( 'Do you want to pus...
python
{ "resource": "" }
q265416
get
validation
def get(f, key, default=None): """ Gets an array from datasets. .. versionadded:: 1.4 """ if key in f.keys(): val = f[key].value if default is None: return val else: if _np.shape(val) == _np.shape(default): return val return def...
python
{ "resource": "" }
q265417
FolderDiff.get_state
validation
def get_state(self): """Get the current directory state""" return [os.path.join(dp, f) for dp, _, fn in os.walk(self.dir) for f in fn]
python
{ "resource": "" }
q265418
ProgressBar.tick
validation
def tick(self): """Add one tick to progress bar""" self.current += 1 if self.current == self.factor: sys.stdout.write('+') sys.stdout.flush() self.current = 0
python
{ "resource": "" }
q265419
DLL.push
validation
def push(self, k): """Push k to the top of the list >>> l = DLL() >>> l.push(1) >>> l [1] >>> l.push(2) >>> l [2, 1] >>> l.push(3) >>> l [3, 2, 1] """ if not self._first: # first item self._f...
python
{ "resource": "" }
q265420
Counter.increment
validation
def increment(cls, name): """Call this method to increment the named counter. This is atomic on the database. :param name: Name for a previously created ``Counter`` object """ with transaction.atomic(): counter = Counter.objects.select_for_update().get(...
python
{ "resource": "" }
q265421
Component.print_loading
validation
def print_loading(self, wait, message): """ print loading message on screen .. note:: loading message only write to `sys.stdout` :param int wait: seconds to wait :param str message: message to print :return: None """ tags = ['\\', '|', '/',...
python
{ "resource": "" }
q265422
Component.warn_message
validation
def warn_message(self, message, fh=None, prefix="[warn]:", suffix="..."): """ print warn type message, if file handle is `sys.stdout`, print color message :param str message: message to print :param file fh: file handle,default is `sys.stdout` :param str prefix: message...
python
{ "resource": "" }
q265423
Component.error_message
validation
def error_message(self, message, fh=None, prefix="[error]:", suffix="..."): """ print error type message if file handle is `sys.stderr`, print color message :param str message: message to print :param file fh: file handle, default is `sys.stdout` :p...
python
{ "resource": "" }
q265424
Component.system
validation
def system(self, cmd, fake_code=False): """ a built-in wrapper make dry-run easier. you should use this instead use `os.system` .. note:: to use it,you need add '--dry-run' option in your argparser options :param str cmd: command to execute :pa...
python
{ "resource": "" }
q265425
Firebase_sync.url_correct
validation
def url_correct(self, point, auth=None, export=None): ''' Returns a Corrected URL to be used for a Request as per the REST API. ''' newUrl = self.__url + point + '.json' if auth or export: newUrl += "?" if auth: newUrl += ("auth=" + auth) ...
python
{ "resource": "" }
q265426
main
validation
def main(): """ Main method. This method holds what you want to execute when the script is run on command line. """ args = get_arguments() setup_logging(args) version_path = os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', '.VERSION' ...
python
{ "resource": "" }
q265427
pickle
validation
def pickle(obj, filepath): """Pickle and compress.""" arr = pkl.dumps(obj, -1) with open(filepath, 'wb') as f: s = 0 while s < len(arr): e = min(s + blosc.MAX_BUFFERSIZE, len(arr)) carr = blosc.compress(arr[s:e], typesize=8) f.write(carr) s = e
python
{ "resource": "" }
q265428
unpickle
validation
def unpickle(filepath): """Decompress and unpickle.""" arr = [] with open(filepath, 'rb') as f: carr = f.read(blosc.MAX_BUFFERSIZE) while len(carr) > 0: arr.append(blosc.decompress(carr)) carr = f.read(blosc.MAX_BUFFERSIZE) return pkl.loads(b"".join(arr))
python
{ "resource": "" }
q265429
contact
validation
def contact(request): """Displays the contact form and sends the email""" form = ContactForm(request.POST or None) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] sender = form.cleaned_data['sender'] cc_myself = form.cleaned_d...
python
{ "resource": "" }
q265430
InitComponent.load_gitconfig
validation
def load_gitconfig(self): """ try use gitconfig info. author,email etc. """ gitconfig_path = os.path.expanduser('~/.gitconfig') if os.path.exists(gitconfig_path): parser = Parser() parser.read(gitconfig_path) parser.sections() ...
python
{ "resource": "" }
q265431
InitComponent.add_arguments
validation
def add_arguments(cls): """ Init project. """ return [ (('--yes',), dict(action='store_true', help='clean .git repo')), (('--variable', '-s'), dict(nargs='+', help='set extra variable,format is name:value')), (('--skip-builtin',), ...
python
{ "resource": "" }
q265432
SlotComponent.run
validation
def run(self, options): """ In general, you don't need to overwrite this method. :param options: :return: """ self.set_signal() self.check_exclusive_mode() slot = self.Handle(self) # start thread i = 0 while i < options.threads:...
python
{ "resource": "" }
q265433
combine_filenames
validation
def combine_filenames(filenames, max_length=40): """Return a new filename to use as the combined file name for a bunch of files, based on the SHA of their contents. A precondition is that they all have the same file extension Given that the list of files can have different paths, we aim to use the ...
python
{ "resource": "" }
q265434
apply_orientation
validation
def apply_orientation(im): """ Extract the oritentation EXIF tag from the image, which should be a PIL Image instance, and if there is an orientation tag that would rotate the image, apply that rotation to the Image instance given to do an in-place rotation. :param Image im: Image instance to inspe...
python
{ "resource": "" }
q265435
write
validation
def write(): """Start a new piece""" click.echo("Fantastic. Let's get started. ") title = click.prompt("What's the title?") # Make sure that title doesn't exist. url = slugify(title) url = click.prompt("What's the URL?", default=url) # Make sure that title doesn't exist. click.echo("Go...
python
{ "resource": "" }
q265436
scaffold
validation
def scaffold(): """Start a new site.""" click.echo("A whole new site? Awesome.") title = click.prompt("What's the title?") url = click.prompt("Great. What's url? http://") # Make sure that title doesn't exist. click.echo("Got it. Creating %s..." % url)
python
{ "resource": "" }
q265437
publish
validation
def publish(): """Publish the site""" try: build_site(dev_mode=False, clean=True) click.echo('Deploying the site...') # call("firebase deploy", shell=True) call("rsync -avz -e ssh --progress %s/ %s" % (BUILD_DIR, CONFIG["scp_target"],), shell=True) if "cloudflare" in CONF...
python
{ "resource": "" }
q265438
Git.get_branches
validation
def get_branches(self): """Returns a list of the branches""" return [self._sanitize(branch) for branch in self._git.branch(color="never").splitlines()]
python
{ "resource": "" }
q265439
Git.get_current_branch
validation
def get_current_branch(self): """Returns the currently active branch""" return next((self._sanitize(branch) for branch in self._git.branch(color="never").splitlines() if branch.startswith('*')), None)
python
{ "resource": "" }
q265440
Git.create_patch
validation
def create_patch(self, from_tag, to_tag): """Create a patch between tags""" return str(self._git.diff('{}..{}'.format(from_tag, to_tag), _tty_out=False))
python
{ "resource": "" }
q265441
one
validation
def one(func, n=0): """ Create a callable that applies ``func`` to a value in a sequence. If the value is not a sequence or is an empty sequence then ``None`` is returned. :type func: `callable` :param func: Callable to be applied to each result. :type n: `int` :param n: Index of th...
python
{ "resource": "" }
q265442
many
validation
def many(func): """ Create a callable that applies ``func`` to every value in a sequence. If the value is not a sequence then an empty list is returned. :type func: `callable` :param func: Callable to be applied to the first result. """ def _many(result): if _isSequenceTypeNotText...
python
{ "resource": "" }
q265443
Text
validation
def Text(value, encoding=None): """ Parse a value as text. :type value: `unicode` or `bytes` :param value: Text value to parse :type encoding: `bytes` :param encoding: Encoding to treat ``bytes`` values as, defaults to ``utf-8``. :rtype: `unicode` :return: Parsed text or ``N...
python
{ "resource": "" }
q265444
Integer
validation
def Integer(value, base=10, encoding=None): """ Parse a value as an integer. :type value: `unicode` or `bytes` :param value: Text value to parse :type base: `unicode` or `bytes` :param base: Base to assume ``value`` is specified in. :type encoding: `bytes` :param encoding: Encoding...
python
{ "resource": "" }
q265445
Boolean
validation
def Boolean(value, true=(u'yes', u'1', u'true'), false=(u'no', u'0', u'false'), encoding=None): """ Parse a value as a boolean. :type value: `unicode` or `bytes` :param value: Text value to parse. :type true: `tuple` of `unicode` :param true: Values to compare, ignoring case, for...
python
{ "resource": "" }
q265446
Delimited
validation
def Delimited(value, parser=Text, delimiter=u',', encoding=None): """ Parse a value as a delimited list. :type value: `unicode` or `bytes` :param value: Text value to parse. :type parser: `callable` taking a `unicode` parameter :param parser: Callable to map over the delimited text values. ...
python
{ "resource": "" }
q265447
Timestamp
validation
def Timestamp(value, _divisor=1., tz=UTC, encoding=None): """ Parse a value as a POSIX timestamp in seconds. :type value: `unicode` or `bytes` :param value: Text value to parse, which should be the number of seconds since the epoch. :type _divisor: `float` :param _divisor: Number to ...
python
{ "resource": "" }
q265448
parse
validation
def parse(expected, query): """ Parse query parameters. :type expected: `dict` mapping `bytes` to `callable` :param expected: Mapping of query argument names to argument parsing callables. :type query: `dict` mapping `bytes` to `list` of `bytes` :param query: Mapping of query argumen...
python
{ "resource": "" }
q265449
CloudWatch.put
validation
def put(self, metrics): """ Put metrics to cloudwatch. Metric shoult be instance or list of instances of CloudWatchMetric """ if type(metrics) == list: for metric in metrics: self.c.put_metric_data(**metric) else: self.c.put_metric_...
python
{ "resource": "" }
q265450
_renderResource
validation
def _renderResource(resource, request): """ Render a given resource. See `IResource.render <twisted:twisted.web.resource.IResource.render>`. """ meth = getattr(resource, 'render_' + nativeString(request.method), None) if meth is None: try: allowedMethods = resource.allowedMe...
python
{ "resource": "" }
q265451
SpinneretResource._adaptToResource
validation
def _adaptToResource(self, result): """ Adapt a result to `IResource`. Several adaptions are tried they are, in order: ``None``, `IRenderable <twisted:twisted.web.iweb.IRenderable>`, `IResource <twisted:twisted.web.resource.IResource>`, and `URLPath <twisted:twisted.pyth...
python
{ "resource": "" }
q265452
SpinneretResource._handleRenderResult
validation
def _handleRenderResult(self, request, result): """ Handle the result from `IResource.render`. If the result is a `Deferred` then return `NOT_DONE_YET` and add a callback to write the result to the request when it arrives. """ def _requestFinished(result, cancel): ...
python
{ "resource": "" }
q265453
ContentTypeNegotiator._negotiateHandler
validation
def _negotiateHandler(self, request): """ Negotiate a handler based on the content types acceptable to the client. :rtype: 2-`tuple` of `twisted.web.iweb.IResource` and `bytes` :return: Pair of a resource and the content type. """ accept = _parseAccept(request.re...
python
{ "resource": "" }
q265454
_parseAccept
validation
def _parseAccept(headers): """ Parse and sort an ``Accept`` header. The header is sorted according to the ``q`` parameter for each header value. @rtype: `OrderedDict` mapping `bytes` to `dict` @return: Mapping of media types to header parameters. """ def sort(value): return float(v...
python
{ "resource": "" }
q265455
_splitHeaders
validation
def _splitHeaders(headers): """ Split an HTTP header whose components are separated with commas. Each component is then split on semicolons and the component arguments converted into a `dict`. @return: `list` of 2-`tuple` of `bytes`, `dict` @return: List of header arguments and mapping of comp...
python
{ "resource": "" }
q265456
contentEncoding
validation
def contentEncoding(requestHeaders, encoding=None): """ Extract an encoding from a ``Content-Type`` header. @type requestHeaders: `twisted.web.http_headers.Headers` @param requestHeaders: Request headers. @type encoding: `bytes` @param encoding: Default encoding to assume if the ``Content-Ty...
python
{ "resource": "" }
q265457
maybe
validation
def maybe(f, default=None): """ Create a nil-safe callable decorator. If the wrapped callable receives ``None`` as its argument, it will return ``None`` immediately. """ @wraps(f) def _maybe(x, *a, **kw): if x is None: return default return f(x, *a, **kw) ret...
python
{ "resource": "" }
q265458
settings
validation
def settings(path=None, with_path=None): """ Get or set `Settings._wrapped` :param str path: a python module file, if user set it,write config to `Settings._wrapped` :param str with_path: search path :return: A instance of `Settings` """ if path: Settings.bind(path, with_pa...
python
{ "resource": "" }
q265459
Settings.bind
validation
def bind(mod_path, with_path=None): """ bind user variable to `_wrapped` .. note:: you don't need call this method by yourself. program will call it in `cliez.parser.parse` .. expection:: if path is not correct,will cause an `ImportError` ...
python
{ "resource": "" }
q265460
get_version
validation
def get_version(): """ Get the version from version module without importing more than necessary. """ version_module_path = os.path.join( os.path.dirname(__file__), "txspinneret", "_version.py") # The version module contains a variable called __version__ with open(version_module_path...
python
{ "resource": "" }
q265461
TX.send
validation
def send(self, use_open_peers=True, queue=True, **kw): """ send a transaction immediately. Failed transactions are picked up by the TxBroadcaster :param ip: specific peer IP to send tx to :param port: port of specific peer :param use_open_peers: use Arky's broadcast method ...
python
{ "resource": "" }
q265462
TX.check_confirmations_or_resend
validation
def check_confirmations_or_resend(self, use_open_peers=False, **kw): """ check if a tx is confirmed, else resend it. :param use_open_peers: select random peers fro api/peers endpoint """ if self.confirmations() == 0: self.send(use_open_peers, **kw)
python
{ "resource": "" }
q265463
command_list
validation
def command_list(): """ Get sub-command list .. note:: Don't use logger handle this function errors. Because the error should be a code error,not runtime error. :return: `list` matched sub-parser """ from cliez.conf import COMPONENT_ROOT root = COMPONENT_ROOT if ro...
python
{ "resource": "" }
q265464
append_arguments
validation
def append_arguments(klass, sub_parsers, default_epilog, general_arguments): """ Add class options to argparser options. :param cliez.component.Component klass: subclass of Component :param Namespace sub_parsers: :param str default_epilog: default_epilog :param list general_arguments: global op...
python
{ "resource": "" }
q265465
parse
validation
def parse(parser, argv=None, settings_key='settings', no_args_func=None): """ parser cliez app :param argparse.ArgumentParser parser: an instance of argparse.ArgumentParser :param argv: argument list,default is `sys.argv` :type argv: list or tuple :param str settings: settings option n...
python
{ "resource": "" }
q265466
hump_to_underscore
validation
def hump_to_underscore(name): """ Convert Hump style to underscore :param name: Hump Character :return: str """ new_name = '' pos = 0 for c in name: if pos == 0: new_name = c.lower() elif 65 <= ord(c) <= 90: new_name += '_' + c.lower() ...
python
{ "resource": "" }
q265467
FuelCheckClient.get_fuel_prices
validation
def get_fuel_prices(self) -> GetFuelPricesResponse: """Fetches fuel prices for all stations.""" response = requests.get( '{}/prices'.format(API_URL_BASE), headers=self._get_headers(), timeout=self._timeout, ) if not response.ok: raise Fuel...
python
{ "resource": "" }
q265468
FuelCheckClient.get_fuel_prices_for_station
validation
def get_fuel_prices_for_station( self, station: int ) -> List[Price]: """Gets the fuel prices for a specific fuel station.""" response = requests.get( '{}/prices/station/{}'.format(API_URL_BASE, station), headers=self._get_headers(), timeou...
python
{ "resource": "" }
q265469
FuelCheckClient.get_fuel_prices_within_radius
validation
def get_fuel_prices_within_radius( self, latitude: float, longitude: float, radius: int, fuel_type: str, brands: Optional[List[str]] = None ) -> List[StationPrice]: """Gets all the fuel prices within the specified radius.""" if brands is None: brands = [] ...
python
{ "resource": "" }
q265470
FuelCheckClient.get_fuel_price_trends
validation
def get_fuel_price_trends(self, latitude: float, longitude: float, fuel_types: List[str]) -> PriceTrends: """Gets the fuel price trends for the given location and fuel types.""" response = requests.post( '{}/prices/trends/'.format(API_URL_BASE), json...
python
{ "resource": "" }
q265471
FuelCheckClient.get_reference_data
validation
def get_reference_data( self, modified_since: Optional[datetime.datetime] = None ) -> GetReferenceDataResponse: """ Fetches API reference data. :param modified_since: The response will be empty if no changes have been made to the reference data since this ...
python
{ "resource": "" }
q265472
PyTemplate.pre
validation
def pre(self, command, output_dir, vars): """ Called before template is applied. """ # import pdb;pdb.set_trace() vars['license_name'] = 'Apache' vars['year'] = time.strftime('%Y', time.localtime())
python
{ "resource": "" }
q265473
Text
validation
def Text(name, encoding=None): """ Match a route parameter. `Any` is a synonym for `Text`. :type name: `bytes` :param name: Route parameter name. :type encoding: `bytes` :param encoding: Default encoding to assume if the ``Content-Type`` header is lacking one. :return: ``ca...
python
{ "resource": "" }
q265474
Integer
validation
def Integer(name, base=10, encoding=None): """ Match an integer route parameter. :type name: `bytes` :param name: Route parameter name. :type base: `int` :param base: Base to interpret the value in. :type encoding: `bytes` :param encoding: Default encoding to assume if the ``Conten...
python
{ "resource": "" }
q265475
_matchRoute
validation
def _matchRoute(components, request, segments, partialMatching): """ Match a request path against our path components. The path components are always matched relative to their parent is in the resource hierarchy, in other words it is only possible to match URIs nested more deeply than the parent re...
python
{ "resource": "" }
q265476
routedResource
validation
def routedResource(f, routerAttribute='router'): """ Decorate a router-producing callable to instead produce a resource. This simply produces a new callable that invokes the original callable, and calls ``resource`` on the ``routerAttribute``. If the router producer has multiple routers the attrib...
python
{ "resource": "" }
q265477
Router._forObject
validation
def _forObject(self, obj): """ Create a new `Router` instance, with it's own set of routes, for ``obj``. """ router = type(self)() router._routes = list(self._routes) router._self = obj return router
python
{ "resource": "" }
q265478
Router._addRoute
validation
def _addRoute(self, f, matcher): """ Add a route handler and matcher to the collection of possible routes. """ self._routes.append((f.func_name, f, matcher))
python
{ "resource": "" }
q265479
Router.route
validation
def route(self, *components): """ See `txspinneret.route.route`. This decorator can be stacked with itself to specify multiple routes with a single handler. """ def _factory(f): self._addRoute(f, route(*components)) return f return _factor...
python
{ "resource": "" }
q265480
Router.subroute
validation
def subroute(self, *components): """ See `txspinneret.route.subroute`. This decorator can be stacked with itself to specify multiple routes with a single handler. """ def _factory(f): self._addRoute(f, subroute(*components)) return f retur...
python
{ "resource": "" }
q265481
_tempfile
validation
def _tempfile(filename): """ Create a NamedTemporaryFile instance to be passed to atomic_writer """ return tempfile.NamedTemporaryFile(mode='w', dir=os.path.dirname(filename), prefix=os.path.basename(filename), ...
python
{ "resource": "" }
q265482
atomic_write
validation
def atomic_write(filename): """ Open a NamedTemoraryFile handle in a context manager """ f = _tempfile(os.fsencode(filename)) try: yield f finally: f.close() # replace the original file with the new temp file (atomic on success) os.replace(f.name, filename)
python
{ "resource": "" }
q265483
get_item
validation
def get_item(filename, uuid): """ Read entry from JSON file """ with open(os.fsencode(str(filename)), "r") as f: data = json.load(f) results = [i for i in data if i["uuid"] == str(uuid)] if results: return results return None
python
{ "resource": "" }
q265484
set_item
validation
def set_item(filename, item): """ Save entry to JSON file """ with atomic_write(os.fsencode(str(filename))) as temp_file: with open(os.fsencode(str(filename))) as products_file: # load the JSON data into memory products_data = json.load(products_file) # check if U...
python
{ "resource": "" }
q265485
update_item
validation
def update_item(filename, item, uuid): """ Update entry by UUID in the JSON file """ with atomic_write(os.fsencode(str(filename))) as temp_file: with open(os.fsencode(str(filename))) as products_file: # load the JSON data into memory products_data = json.load(products_fil...
python
{ "resource": "" }
q265486
Command.command_handle
validation
def command_handle(self): """Get the number of the shell command.""" self.__results = self.execute(self.args.command) self.close() self.logger.debug("results: {}".format(self.__results)) if not self.__results: self.unknown("{} return nothing.".format(self.args.comman...
python
{ "resource": "" }
q265487
Ssh.execute
validation
def execute(self, command, timeout=None): """Execute a shell command.""" try: self.channel = self.ssh.get_transport().open_session() except paramiko.SSHException as e: self.unknown("Create channel error: %s" % e) try: self.channel.settimeout(self.args....
python
{ "resource": "" }
q265488
slinky
validation
def slinky(filename, seconds_available, bucket_name, aws_key, aws_secret): """Simple program that creates an temp S3 link.""" if not os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'): print 'Need to set environment variables for AWS access and create a slinky bucket.' exi...
python
{ "resource": "" }
q265489
Process.check_readable
validation
def check_readable(self, timeout): """ Poll ``self.stdout`` and return True if it is readable. :param float timeout: seconds to wait I/O :return: True if readable, else False :rtype: boolean """ rlist, wlist, xlist = select.select([self._stdout], [], [], timeout)...
python
{ "resource": "" }
q265490
get_indices_list
validation
def get_indices_list(s: Any) -> List[str]: """ Retrieve a list of characters and escape codes where each escape code uses only one index. The indexes will not match up with the indexes in the original string. """ indices = get_indices(s) return [ indices[i] for i in sorted(indice...
python
{ "resource": "" }
q265491
strip_codes
validation
def strip_codes(s: Any) -> str: """ Strip all color codes from a string. Returns empty string for "falsey" inputs. """ return codepat.sub('', str(s) if (s or (s == 0)) else '')
python
{ "resource": "" }
q265492
AbstractBundle.init_build
validation
def init_build(self, asset, builder): """ Called when builder group collect files Resolves absolute url if relative passed :type asset: static_bundle.builders.Asset :type builder: static_bundle.builders.StandardBuilder """ if not self.abs_path: rel_pa...
python
{ "resource": "" }
q265493
AbstractBundle.add_file
validation
def add_file(self, *args): """ Add single file or list of files to bundle :type: file_path: str|unicode """ for file_path in args: self.files.append(FilePath(file_path, self))
python
{ "resource": "" }
q265494
AbstractBundle.add_directory
validation
def add_directory(self, *args, **kwargs): """ Add directory or directories list to bundle :param exclusions: List of excluded paths :type path: str|unicode :type exclusions: list """ exc = kwargs.get('exclusions', None) for path in args: self...
python
{ "resource": "" }
q265495
AbstractBundle.add_path_object
validation
def add_path_object(self, *args): """ Add custom path objects :type: path_object: static_bundle.paths.AbstractPath """ for obj in args: obj.bundle = self self.files.append(obj)
python
{ "resource": "" }
q265496
AbstractBundle.add_prepare_handler
validation
def add_prepare_handler(self, prepare_handlers): """ Add prepare handler to bundle :type: prepare_handler: static_bundle.handlers.AbstractPrepareHandler """ if not isinstance(prepare_handlers, static_bundle.BUNDLE_ITERABLE_TYPES): prepare_handlers = [prepare_handlers...
python
{ "resource": "" }
q265497
AbstractBundle.prepare
validation
def prepare(self): """ Called when builder run collect files in builder group :rtype: list[static_bundle.files.StaticFileResult] """ result_files = self.collect_files() chain = self.prepare_handlers_chain if chain is None: # default handlers ...
python
{ "resource": "" }
q265498
FileNumber.filenumber_handle
validation
def filenumber_handle(self): """Get the number of files in the folder.""" self.__results = [] self.__dirs = [] self.__files = [] self.__ftp = self.connect() self.__ftp.dir(self.args.path, self.__results.append) self.logger.debug("dir results: {}".format(self.__res...
python
{ "resource": "" }
q265499
DataStore.register_json
validation
def register_json(self, data): """ Register the contents as JSON """ j = json.loads(data) self.last_data_timestamp = \ datetime.datetime.utcnow().replace(microsecond=0).isoformat() try: for v in j: # prepare the sensor entry con...
python
{ "resource": "" }