_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q5200
cached_property
train
def cached_property(**kwargs): """Cache the return value of a property.""" def decorator(function): @wraps(function) def wrapper(self): key = 'fandjango.%(model)s.%(property)s_%(pk)s' % { 'model': self.__class__.__name__, 'pk': self.pk, ...
python
{ "resource": "" }
q5201
authorization_denied_view
train
def authorization_denied_view(request): """Proxy for the view referenced in ``FANDJANGO_AUTHORIZATION_DENIED_VIEW``.""" authorization_denied_module_name = AUTHORIZATION_DENIED_VIEW.rsplit('.', 1)[0] authorization_denied_view_name = AUTHORIZATION_DENIED_VIEW.split('.')[-1] authorization_denied_module = ...
python
{ "resource": "" }
q5202
get_post_authorization_redirect_url
train
def get_post_authorization_redirect_url(request, canvas=True): """ Determine the URL users should be redirected to upon authorization the application. If request is non-canvas use user defined site url if set, else the site hostname. """ path = request.get_full_path() if canvas: if FA...
python
{ "resource": "" }
q5203
get_full_path
train
def get_full_path(request, remove_querystrings=[]): """Gets the current path, removing specified querstrings""" path = request.get_full_path() for qs in remove_querystrings: path = re.sub(r'&?' + qs + '=?(.+)?&?', '', path) return path
python
{ "resource": "" }
q5204
authorize_application
train
def authorize_application( request, redirect_uri = 'https://%s/%s' % (FACEBOOK_APPLICATION_DOMAIN, FACEBOOK_APPLICATION_NAMESPACE), permissions = FACEBOOK_APPLICATION_INITIAL_PERMISSIONS ): """ Redirect the user to authorize the application. Redirection is done by rendering a JavaScript sni...
python
{ "resource": "" }
q5205
deauthorize_application
train
def deauthorize_application(request): """ When a user deauthorizes an application, Facebook sends a HTTP POST request to the application's "deauthorization callback" URL. This view picks up on requests of this sort and marks the corresponding users as unauthorized. """ if request.facebook: ...
python
{ "resource": "" }
q5206
SqlQuery.make_update
train
def make_update(cls, table, set_query, where=None): """ Make UPDATE query. :param str table: Table name of executing the query. :param str set_query: SET part of the UPDATE query. :param str where: Add a WHERE clause to execute query, if the value is not ...
python
{ "resource": "" }
q5207
SqlQuery.make_where_in
train
def make_where_in(cls, key, value_list): """ Make part of WHERE IN query. :param str key: Attribute name of the key. :param str value_list: List of values that the right hand side associated with the key. :return: Part of WHERE query of SQLite. :rtype: str ...
python
{ "resource": "" }
q5208
SimpleSQLite.connect
train
def connect(self, database_path, mode="a"): """ Connect to a SQLite database. :param str database_path: Path to the SQLite database file to be connected. :param str mode: ``"r"``: Open for read only. ``"w"``: Open for read/write. Delete ex...
python
{ "resource": "" }
q5209
SimpleSQLite.execute_query
train
def execute_query(self, query, caller=None): """ Send arbitrary SQLite query to the database. :param str query: Query to executed. :param tuple caller: Caller information. Expects the return value of :py:meth:`logging.Logger.findCaller`. :return: The resu...
python
{ "resource": "" }
q5210
SimpleSQLite.select
train
def select(self, select, table_name, where=None, extra=None): """ Send a SELECT query to the database. :param str select: Attribute for the ``SELECT`` query. :param str table_name: |arg_select_table_name| :param where: |arg_select_where| :type where: |arg_where_type| ...
python
{ "resource": "" }
q5211
SimpleSQLite.select_as_dict
train
def select_as_dict(self, table_name, columns=None, where=None, extra=None): """ Get data in the database and return fetched data as a |OrderedDict| list. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param where: |arg_sel...
python
{ "resource": "" }
q5212
SimpleSQLite.select_as_memdb
train
def select_as_memdb(self, table_name, columns=None, where=None, extra=None): """ Get data in the database and return fetched data as a in-memory |SimpleSQLite| instance. :param str table_name: |arg_select_table_name| :param list columns: |arg_select_as_xx_columns| :param...
python
{ "resource": "" }
q5213
SimpleSQLite.insert
train
def insert(self, table_name, record, attr_names=None): """ Send an INSERT query to the database. :param str table_name: Table name of executing the query. :param record: Record to be inserted. :type record: |dict|/|namedtuple|/|list|/|tuple| :raises IOError: |raises_writ...
python
{ "resource": "" }
q5214
SimpleSQLite.insert_many
train
def insert_many(self, table_name, records, attr_names=None): """ Send an INSERT query with multiple records to the database. :param str table: Table name of executing the query. :param records: Records to be inserted. :type records: list of |dict|/|namedtuple|/|list|/|tuple| ...
python
{ "resource": "" }
q5215
SimpleSQLite.update
train
def update(self, table_name, set_query, where=None): """Execute an UPDATE query. Args: table_name (|str|): Table name of executing the query. set_query (|str|): ``SET`` clause for the update query. where (|arg_where_type| , optional): ...
python
{ "resource": "" }
q5216
SimpleSQLite.delete
train
def delete(self, table_name, where=None): """ Send a DELETE query to the database. :param str table_name: Table name of executing the query. :param where: |arg_select_where| :type where: |arg_where_type| """ self.validate_access_permission(["w", "a"]) se...
python
{ "resource": "" }
q5217
SimpleSQLite.fetch_value
train
def fetch_value(self, select, table_name, where=None, extra=None): """ Fetch a value from the table. Return |None| if no value matches the conditions, or the table not found in the database. :param str select: Attribute for SELECT query :param str table_name: Table name of execu...
python
{ "resource": "" }
q5218
SimpleSQLite.fetch_num_records
train
def fetch_num_records(self, table_name, where=None): """ Fetch the number of records in a table. :param str table_name: Table name to get number of records. :param where: |arg_select_where| :type where: |arg_where_type| :return: Number of records in the table...
python
{ "resource": "" }
q5219
SimpleSQLite.get_profile
train
def get_profile(self, profile_count=50): """ Get profile of query execution time. :param int profile_count: Number of profiles to retrieve, counted from the top query in descending order by the cumulative execution time. :return: Profile information f...
python
{ "resource": "" }
q5220
SimpleSQLite.create_table_from_data_matrix
train
def create_table_from_data_matrix( self, table_name, attr_names, data_matrix, primary_key=None, add_primary_key_column=False, index_attrs=None, ): """ Create a table if not exists. Moreover, insert data into the created table. ...
python
{ "resource": "" }
q5221
SimpleSQLite.create_table_from_dataframe
train
def create_table_from_dataframe( self, dataframe, table_name="", primary_key=None, add_primary_key_column=False, index_attrs=None, ): """ Create a table from a pandas.DataFrame instance. :param pandas.DataFrame dataframe: DataFrame instance to...
python
{ "resource": "" }
q5222
SimpleSQLite.close
train
def close(self): """ Commit and close the connection. .. seealso:: :py:meth:`sqlite3.Connection.close` """ if self.__delayed_connection_path and self.__connection is None: self.__initialize_connection() return try: self.check_connect...
python
{ "resource": "" }
q5223
SimpleSQLite.__extract_col_type_from_tabledata
train
def __extract_col_type_from_tabledata(table_data): """ Extract data type name for each column as SQLite names. :param tabledata.TableData table_data: :return: { column_number : column_data_type } :rtype: dictionary """ typename_table = { typepy.Typec...
python
{ "resource": "" }
q5224
copy_table
train
def copy_table(src_con, dst_con, src_table_name, dst_table_name, is_overwrite=True): """ Copy a table from source to destination. :param SimpleSQLite src_con: Connection to the source database. :param SimpleSQLite dst_con: Connection to the destination database. :param str src_table_name: Source ta...
python
{ "resource": "" }
q5225
get_builtin_date
train
def get_builtin_date(date, date_format="%Y-%m-%dT%H:%M:%S", raise_exception=False): """ Try to convert a date to a builtin instance of ``datetime.datetime``. The input date can be a ``str``, a ``datetime.datetime``, a ``xmlrpc.client.Datetime`` or a ``xmlrpclib.Datetime`` instance. The returned object i...
python
{ "resource": "" }
q5226
user_in_group
train
def user_in_group(user, group): """Returns True if the given user is in given group""" if isinstance(group, Group): return user_is_superuser(user) or group in user.groups.all() elif isinstance(group, six.string_types): return user_is_superuser(user) or user.groups.filter(name=group).exists()...
python
{ "resource": "" }
q5227
user_in_any_group
train
def user_in_any_group(user, groups): """Returns True if the given user is in at least 1 of the given groups""" return user_is_superuser(user) or any(user_in_group(user, group) for group in groups)
python
{ "resource": "" }
q5228
user_in_all_groups
train
def user_in_all_groups(user, groups): """Returns True if the given user is in all given groups""" return user_is_superuser(user) or all(user_in_group(user, group) for group in groups)
python
{ "resource": "" }
q5229
RPCEntryPoint.get_handler_classes
train
def get_handler_classes(self): """Return the list of handlers to use when receiving RPC requests.""" handler_classes = [import_string(handler_cls) for handler_cls in settings.MODERNRPC_HANDLERS] if self.protocol == ALL: return handler_classes else: return [cls f...
python
{ "resource": "" }
q5230
RPCEntryPoint.post
train
def post(self, request, *args, **kwargs): """ Handle a XML-RPC or JSON-RPC request. :param request: Incoming request :param args: Additional arguments :param kwargs: Additional named arguments :return: A HttpResponse containing XML-RPC or JSON-RPC response, depending on ...
python
{ "resource": "" }
q5231
RPCEntryPoint.get_context_data
train
def get_context_data(self, **kwargs): """Update context data with list of RPC methods of the current entry point. Will be used to display methods documentation page""" kwargs.update({ 'methods': registry.get_all_methods(self.entry_point, sort_methods=True), }) return ...
python
{ "resource": "" }
q5232
ModernRpcConfig.rpc_methods_registration
train
def rpc_methods_registration(): """Look into each module listed in settings.MODERNRPC_METHODS_MODULES, import each module and register functions annotated with @rpc_method decorator in the registry""" # In previous version, django-modern-rpc used the django cache system to store methods registr...
python
{ "resource": "" }
q5233
http_basic_auth_login_required
train
def http_basic_auth_login_required(func=None): """Decorator. Use it to specify a RPC method is available only to logged users""" wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_authenticated]) # If @http_basic_auth_login_required() is used (with parenthesis) if fu...
python
{ "resource": "" }
q5234
http_basic_auth_superuser_required
train
def http_basic_auth_superuser_required(func=None): """Decorator. Use it to specify a RPC method is available only to logged superusers""" wrapper = auth.set_authentication_predicate(http_basic_auth_check_user, [auth.user_is_superuser]) # If @http_basic_auth_superuser_required() is used (with parenthesis) ...
python
{ "resource": "" }
q5235
rpc_method
train
def rpc_method(func=None, name=None, entry_point=ALL, protocol=ALL, str_standardization=settings.MODERNRPC_PY2_STR_TYPE, str_standardization_encoding=settings.MODERNRPC_PY2_STR_ENCODING): """ Mark a standard python function as RPC method. All arguments are optional :param...
python
{ "resource": "" }
q5236
RPCMethod.parse_docstring
train
def parse_docstring(self, content): """ Parse the given full docstring, and extract method description, arguments, and return documentation. This method try to find arguments description and types, and put the information in "args_doc" and "signature" members. Also parse return type and...
python
{ "resource": "" }
q5237
RPCMethod.html_doc
train
def html_doc(self): """Methods docstring, as HTML""" if not self.raw_docstring: result = '' elif settings.MODERNRPC_DOC_FORMAT.lower() in ('rst', 'restructred', 'restructuredtext'): from docutils.core import publish_parts result = publish_parts(self.raw_docst...
python
{ "resource": "" }
q5238
RPCMethod.available_for_protocol
train
def available_for_protocol(self, protocol): """Check if the current function can be executed from a request defining the given protocol""" if self.protocol == ALL or protocol == ALL: return True return protocol in ensure_sequence(self.protocol)
python
{ "resource": "" }
q5239
RPCMethod.available_for_entry_point
train
def available_for_entry_point(self, entry_point): """Check if the current function can be executed from a request to the given entry point""" if self.entry_point == ALL or entry_point == ALL: return True return entry_point in ensure_sequence(self.entry_point)
python
{ "resource": "" }
q5240
RPCMethod.is_valid_for
train
def is_valid_for(self, entry_point, protocol): """Check if the current function can be executed from a request to the given entry point and with the given protocol""" return self.available_for_entry_point(entry_point) and self.available_for_protocol(protocol)
python
{ "resource": "" }
q5241
RPCMethod.is_return_doc_available
train
def is_return_doc_available(self): """Returns True if this method's return is documented""" return bool(self.return_doc and (self.return_doc.get('text') or self.return_doc.get('type')))
python
{ "resource": "" }
q5242
_RPCRegistry.register_method
train
def register_method(self, func): """ Register a function to be available as RPC method. The given function will be inspected to find external_name, protocol and entry_point values set by the decorator @rpc_method. :param func: A function previously decorated using @rpc_method ...
python
{ "resource": "" }
q5243
_RPCRegistry.get_method
train
def get_method(self, name, entry_point, protocol): """Retrieve a method from the given name""" if name in self._registry and self._registry[name].is_valid_for(entry_point, protocol): return self._registry[name] return None
python
{ "resource": "" }
q5244
logger_has_handlers
train
def logger_has_handlers(logger): """ Check if given logger has at least 1 handler associated, return a boolean value. Since Python 2 doesn't provide Logger.hasHandlers(), we have to perform the lookup by ourself. """ if six.PY3: return logger.hasHandlers() else: c = logger ...
python
{ "resource": "" }
q5245
get_modernrpc_logger
train
def get_modernrpc_logger(name): """Get a logger from default logging manager. If no handler is associated, add a default NullHandler""" logger = logging.getLogger(name) if not logger_has_handlers(logger): # If logging is not configured in the current project, configure this logger to discard all log...
python
{ "resource": "" }
q5246
RPCHandler.execute_procedure
train
def execute_procedure(self, name, args=None, kwargs=None): """ Call the concrete python function corresponding to given RPC Method `name` and return the result. Raise RPCUnknownMethod, AuthenticationFailed, RPCInvalidParams or any Exception sub-class. """ _method = registry.get...
python
{ "resource": "" }
q5247
__system_listMethods
train
def __system_listMethods(**kwargs): """Returns a list of all methods available in the current entry point""" entry_point = kwargs.get(ENTRY_POINT_KEY) protocol = kwargs.get(PROTOCOL_KEY) return registry.get_all_method_names(entry_point, protocol, sort_methods=True)
python
{ "resource": "" }
q5248
__system_methodSignature
train
def __system_methodSignature(method_name, **kwargs): """ Returns an array describing the signature of the given method name. The result is an array with: - Return type as first elements - Types of method arguments from element 1 to N :param method_name: Name of a method available for current ...
python
{ "resource": "" }
q5249
__system_methodHelp
train
def __system_methodHelp(method_name, **kwargs): """ Returns the documentation of the given method name. :param method_name: Name of a method available for current entry point (and protocol) :param kwargs: :return: Documentation text for the RPC method """ entry_point = kwargs.get(ENTRY_POIN...
python
{ "resource": "" }
q5250
__system_multiCall
train
def __system_multiCall(calls, **kwargs): """ Call multiple RPC methods at once. :param calls: An array of struct like {"methodName": string, "params": array } :param kwargs: Internal data :type calls: list :type kwargs: dict :return: """ if not isinstance(calls, list): raise...
python
{ "resource": "" }
q5251
acquire_code
train
def acquire_code(args, session, session3): """returns the user's token serial number, MFA token code, and an error code.""" serial_number = find_mfa_for_user(args.serial_number, session, session3) if not serial_number: print("There are no MFA devices associated with this user.", fi...
python
{ "resource": "" }
q5252
rotate
train
def rotate(args, credentials): """rotate the identity profile's AWS access key pair.""" current_access_key_id = credentials.get( args.identity_profile, 'aws_access_key_id') # create new sessions using the MFA credentials session, session3, err = make_session(args.target_profile) if err: ...
python
{ "resource": "" }
q5253
BaseField.coerce
train
def coerce(self, value): """Coerce a cleaned value.""" if self._coerce is not None: value = self._coerce(value) return value
python
{ "resource": "" }
q5254
Item.all_from
train
def all_from(cls, *args, **kwargs): """Query for items passing PyQuery args explicitly.""" pq_items = cls._get_items(*args, **kwargs) return [cls(item=i) for i in pq_items.items()]
python
{ "resource": "" }
q5255
Item.all
train
def all(cls, path=''): """Return all ocurrences of the item.""" url = urljoin(cls._meta.base_url, path) pq_items = cls._get_items(url=url, **cls._meta._pyquery_kwargs) return [cls(item=i) for i in pq_items.items()]
python
{ "resource": "" }
q5256
Customer.info
train
def info(self, id, attributes=None): """ Retrieve customer data :param id: ID of customer :param attributes: `List` of attributes needed """ if attributes: return self.call('customer.info', [id, attributes]) else: return self.call('custome...
python
{ "resource": "" }
q5257
Order.search
train
def search(self, filters=None, fields=None, limit=None, page=1): """ Retrieve order list by options using search api. Using this result can be paginated :param options: Dictionary of options. :param filters: `{<attribute>:{<operator>:<value>}}` :param fields: [<String: ...
python
{ "resource": "" }
q5258
Order.addcomment
train
def addcomment(self, order_increment_id, status, comment=None, notify=False): """ Add comment to order or change its state :param order_increment_id: Order ID TODO: Identify possible values for status """ if comment is None: comment = "" r...
python
{ "resource": "" }
q5259
CreditMemo.create
train
def create( self, order_increment_id, creditmemo_data=None, comment=None, email=False, include_comment=False, refund_to_store_credit_amount=None): """ Create new credit_memo for order :param order_increment_id: ...
python
{ "resource": "" }
q5260
CreditMemo.addcomment
train
def addcomment(self, creditmemo_increment_id, comment, email=True, include_in_email=False): """ Add new comment to credit memo :param creditmemo_increment_id: Credit memo increment ID :return: bool """ return bool( self.call( 'sal...
python
{ "resource": "" }
q5261
Shipment.create
train
def create(self, order_increment_id, items_qty, comment=None, email=True, include_comment=False): """ Create new shipment for order :param order_increment_id: Order Increment ID :type order_increment_id: str :param items_qty: items qty to ship :type items_qty...
python
{ "resource": "" }
q5262
Shipment.addtrack
train
def addtrack(self, shipment_increment_id, carrier, title, track_number): """ Add new tracking number :param shipment_increment_id: Shipment ID :param carrier: Carrier Code :param title: Tracking title :param track_number: Tracking Number """ return self.c...
python
{ "resource": "" }
q5263
Invoice.addcomment
train
def addcomment(self, invoice_increment_id, comment=None, email=False, include_comment=False): """ Add comment to invoice or change its state :param invoice_increment_id: Invoice ID """ if comment is None: comment = "" return bool( self...
python
{ "resource": "" }
q5264
Category.info
train
def info(self, category_id, store_view=None, attributes=None): """ Retrieve Category details :param category_id: ID of category to retrieve :param store_view: Store view ID or code :param attributes: Return the fields specified :return: Dictionary of data """ ...
python
{ "resource": "" }
q5265
Category.create
train
def create(self, parent_id, data, store_view=None): """ Create new category and return its ID :param parent_id: ID of parent :param data: Data for category :param store_view: Store view ID or Code :return: Integer ID """ return int(self.call( ...
python
{ "resource": "" }
q5266
Category.move
train
def move(self, category_id, parent_id, after_id=None): """ Move category in tree :param category_id: ID of category to move :param parent_id: New parent of the category :param after_id: Category ID after what position it will be moved :return: Boolean """ ...
python
{ "resource": "" }
q5267
Category.assignproduct
train
def assignproduct(self, category_id, product, position=None): """ Assign product to a category :param category_id: ID of a category :param product: ID or Code of the product :param position: Position of product in category :return: boolean """ return boo...
python
{ "resource": "" }
q5268
Category.updateproduct
train
def updateproduct(self, category_id, product, position=None): """ Update assigned product :param category_id: ID of a category :param product: ID or Code of the product :param position: Position of product in category :return: boolean """ return bool(sel...
python
{ "resource": "" }
q5269
Product.info
train
def info(self, product, store_view=None, attributes=None, identifierType=None): """ Retrieve product data :param product: ID or SKU of product :param store_view: ID or Code of store view :param attributes: List of fields required :param identifierType: Defin...
python
{ "resource": "" }
q5270
Product.create
train
def create(self, product_type, attribute_set_id, sku, data): """ Create Product and return ID :param product_type: String type of product :param attribute_set_id: ID of attribute set :param sku: SKU of the product :param data: Dictionary of data :return: INT id o...
python
{ "resource": "" }
q5271
Product.update
train
def update(self, product, data, store_view=None, identifierType=None): """ Update product Information :param product: ID or SKU of product :param data: Dictionary of attributes to update :param store_view: ID or Code of store view :param identifierType: Defines whether t...
python
{ "resource": "" }
q5272
Product.setSpecialPrice
train
def setSpecialPrice(self, product, special_price=None, from_date=None, to_date=None, store_view=None, identifierType=None): """ Update product's special price :param product: ID or SKU of product :param special_price: Special Price ...
python
{ "resource": "" }
q5273
Product.getSpecialPrice
train
def getSpecialPrice(self, product, store_view=None, identifierType=None): """ Get product special price data :param product: ID or SKU of product :param store_view: ID or Code of Store view :param identifierType: Defines whether the product or SKU value is ...
python
{ "resource": "" }
q5274
ProductImages.list
train
def list(self, product, store_view=None, identifierType=None): """ Retrieve product image list :param product: ID or SKU of product :param store_view: Code or ID of store view :param identifierType: Defines whether the product or SKU value is passe...
python
{ "resource": "" }
q5275
ProductImages.info
train
def info(self, product, image_file, store_view=None, identifierType=None): """ Retrieve product image data :param product: ID or SKU of product :param store_view: ID or Code of store view :param attributes: List of fields required :param identifierType: Defines whether t...
python
{ "resource": "" }
q5276
ProductImages.create
train
def create(self, product, data, store_view=None, identifierType=None): """ Upload a new product image. :param product: ID or SKU of product :param data: `dict` of image data (label, position, exclude, types) Example: { 'label': 'description of photo', 'positi...
python
{ "resource": "" }
q5277
ProductImages.update
train
def update(self, product, img_file_name, data, store_view=None, identifierType=None): """ Update a product image. :param product: ID or SKU of product :param img_file_name: The image file name Example: '/m/y/my_image_thumb.jpg' :param data: `dict` of i...
python
{ "resource": "" }
q5278
ProductImages.remove
train
def remove(self, product, img_file_name, identifierType=None): """ Remove a product image. :param product: ID or SKU of product :param img_file_name: The image file name Example: '/m/y/my_image_thumb.jpg' :param identifierType: Defines whether the product or SKU valu...
python
{ "resource": "" }
q5279
ProductLinks.list
train
def list(self, link_type, product, identifierType=None): """ Retrieve list of linked products :param link_type: type of link, one of 'cross_sell', 'up_sell', 'related' or 'grouped' :param product: ID or SKU of product :param identifierType: Defines whether the pr...
python
{ "resource": "" }
q5280
ProductLinks.assign
train
def assign(self, link_type, product, linked_product, data=None, identifierType=None): """ Assign a product link :param link_type: type of link, one of 'cross_sell', 'up_sell', 'related' or 'grouped' :param product: ID or SKU of product :param linke...
python
{ "resource": "" }
q5281
ProductLinks.remove
train
def remove(self, link_type, product, linked_product, identifierType=None): """ Remove a product link :param link_type: type of link, one of 'cross_sell', 'up_sell', 'related' or 'grouped' :param product: ID or SKU of product :param linked_product: ID or SKU of li...
python
{ "resource": "" }
q5282
ProductConfigurable.update
train
def update(self, product, linked_products, attributes): """ Configurable Update product :param product: ID or SKU of product :param linked_products: List ID or SKU of linked product to link :param attributes: dicc :return: True/False """ return bool(self....
python
{ "resource": "" }
q5283
CartCoupon.add
train
def add(self, quote_id, coupon_code, store_view=None): """ Add a coupon code to a quote. :param quote_id: Shopping cart ID (quote ID) :param coupon_code, string, Coupon code :param store_view: Store view ID or code :return: boolean, True if the coupon code is added ...
python
{ "resource": "" }
q5284
CartProduct.move_to_customer_quote
train
def move_to_customer_quote(self, quote_id, product_data, store_view=None): """ Allows you to move products from the current quote to a customer quote. :param quote_id: Shopping cart ID (quote ID) :param product_data, list of dicts of product details, example [ ...
python
{ "resource": "" }
q5285
pack
train
def pack(ctx, remove_lib=True): """Build a isolated runnable package. """ OUTPUT_DIR.mkdir(parents=True, exist_ok=True) with ROOT.joinpath('Pipfile.lock').open() as f: lockfile = plette.Lockfile.load(f) libdir = OUTPUT_DIR.joinpath('lib') paths = {'purelib': libdir, 'platlib': libdir} ...
python
{ "resource": "" }
q5286
extract_feed
train
def extract_feed( inpath: str, outpath: str, view: View, config: nx.DiGraph = None ) -> str: """Extract a subset of a GTFS zip into a new file""" config = default_config() if config is None else config config = remove_node_attributes(config, "converters") feed = load_feed(inpath, view, config) r...
python
{ "resource": "" }
q5287
write_feed_dangerously
train
def write_feed_dangerously( feed: Feed, outpath: str, nodes: Optional[Collection[str]] = None ) -> str: """Naively write a feed to a zipfile This function provides no sanity checks. Use it at your own risk. """ nodes = DEFAULT_NODES if nodes is None else nodes try: tmpdir = tempfile...
python
{ "resource": "" }
q5288
read_busiest_date
train
def read_busiest_date(path: str) -> Tuple[datetime.date, FrozenSet[str]]: """Find the earliest date with the most trips""" feed = load_raw_feed(path) return _busiest_date(feed)
python
{ "resource": "" }
q5289
read_busiest_week
train
def read_busiest_week(path: str) -> Dict[datetime.date, FrozenSet[str]]: """Find the earliest week with the most trips""" feed = load_raw_feed(path) return _busiest_week(feed)
python
{ "resource": "" }
q5290
read_service_ids_by_date
train
def read_service_ids_by_date(path: str) -> Dict[datetime.date, FrozenSet[str]]: """Find all service identifiers by date""" feed = load_raw_feed(path) return _service_ids_by_date(feed)
python
{ "resource": "" }
q5291
read_dates_by_service_ids
train
def read_dates_by_service_ids( path: str ) -> Dict[FrozenSet[str], FrozenSet[datetime.date]]: """Find dates with identical service""" feed = load_raw_feed(path) return _dates_by_service_ids(feed)
python
{ "resource": "" }
q5292
read_trip_counts_by_date
train
def read_trip_counts_by_date(path: str) -> Dict[datetime.date, int]: """A useful proxy for busyness""" feed = load_raw_feed(path) return _trip_counts_by_date(feed)
python
{ "resource": "" }
q5293
_load_feed
train
def _load_feed(path: str, view: View, config: nx.DiGraph) -> Feed: """Multi-file feed filtering""" config_ = remove_node_attributes(config, ["converters", "transformations"]) feed_ = Feed(path, view={}, config=config_) for filename, column_filters in view.items(): config_ = reroot_graph(config_,...
python
{ "resource": "" }
q5294
Feed._filter
train
def _filter(self, filename: str, df: pd.DataFrame) -> pd.DataFrame: """Apply view filters""" view = self._view.get(filename) if view is None: return df for col, values in view.items(): # If applicable, filter this dataframe by the given set of values ...
python
{ "resource": "" }
q5295
Feed._prune
train
def _prune(self, filename: str, df: pd.DataFrame) -> pd.DataFrame: """Depth-first search through the dependency graph and prune dependent DataFrames along the way. """ dependencies = [] for _, depf, data in self._config.out_edges(filename, data=True): deps = data.get(...
python
{ "resource": "" }
q5296
Feed._convert_types
train
def _convert_types(self, filename: str, df: pd.DataFrame) -> None: """ Apply type conversions """ if df.empty: return converters = self._config.nodes.get(filename, {}).get("converters", {}) for col, converter in converters.items(): if col in df.co...
python
{ "resource": "" }
q5297
reroot_graph
train
def reroot_graph(G: nx.DiGraph, node: str) -> nx.DiGraph: """Return a copy of the graph rooted at the given node""" G = G.copy() for n, successors in list(nx.bfs_successors(G, source=node)): for s in successors: G.add_edge(s, n, **G.edges[n, s]) G.remove_edge(n, s) return...
python
{ "resource": "" }
q5298
setwrap
train
def setwrap(value: Any) -> Set[str]: """ Returns a flattened and stringified set from the given object or iterable. For use in public functions which accept argmuents or kwargs that can be one object or a list of objects. """ return set(map(str, set(flatten([value]))))
python
{ "resource": "" }
q5299
remove_node_attributes
train
def remove_node_attributes(G: nx.DiGraph, attributes: Union[str, Iterable[str]]): """ Return a copy of the graph with the given attributes deleted from all nodes. """ G = G.copy() for _, data in G.nodes(data=True): for attribute in setwrap(attributes): if attribute in data: ...
python
{ "resource": "" }