Search is not available for this dataset
text
stringlengths
75
104k
def _delete_tasks(config, task_id, limit=100, offset=0): """Delete tasks from a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, config.all) if task_id: ...
def _update_tasks_redundancy(config, task_id, redundancy, limit=300, offset=0): """Update tasks redundancy from a project.""" try: project = find_project_by_short_name(config.project['short_name'], config.pbclient, ...
def find_project_by_short_name(short_name, pbclient, all=None): """Return project by short_name.""" try: response = pbclient.find_project(short_name=short_name, all=all) check_api_error(response) if (len(response) == 0): msg = '%s not found! You can use the all=1 argument to ...
def check_api_error(api_response): print(api_response) """Check if returned API response contains an error.""" if type(api_response) == dict and 'code' in api_response and api_response['code'] <> 200: print("Server response code: %s" % api_response['code']) print("Server response: %s...
def format_error(module, error): """Format the error for the given module.""" logging.error(module) # Beautify JSON error print error.message print json.dumps(error.error, sort_keys=True, indent=4, separators=(',', ': ')) exit(1)
def create_task_info(task): """Create task_info field.""" task_info = None if task.get('info'): task_info = task['info'] else: task_info = task return task_info
def create_helping_material_info(helping): """Create helping_material_info field.""" helping_info = None file_path = None if helping.get('info'): helping_info = helping['info'] else: helping_info = helping if helping_info.get('file_path'): file_path = helping_info.get('fi...
def fetch_by_code(self, code): """ Returns data belonging to an authorization code from redis or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`. """ code_data = self.read(code) if code_data is None: raise AuthCodeNotFound ...
def save_code(self, authorization_code): """ Stores the data belonging to an authorization code token in redis. See :class:`oauth2.store.AuthCodeStore`. """ self.write(authorization_code.code, {"client_id": authorization_code.client_id, "c...
def save_token(self, access_token): """ Stores the access token and additional data in redis. See :class:`oauth2.store.AccessTokenStore`. """ self.write(access_token.token, access_token.__dict__) unique_token_key = self._unique_token_key(access_token.client_id, ...
def delete_refresh_token(self, refresh_token): """ Deletes a refresh token after use :param refresh_token: The refresh token to delete. """ access_token = self.fetch_by_refresh_token(refresh_token) self.delete(access_token.token)
def add_client(self, client_id, client_secret, redirect_uris, authorized_grants=None, authorized_response_types=None): """ Add a client app. :param client_id: Identifier of the client app. :param client_secret: Secret the client app uses for authentication ...
def create_access_token_data(self, grant_type): """ Create data needed by an access token. :param grant_type: :type grant_type: str :return: A ``dict`` containing he ``access_token`` and the ``token_type``. If the value of ``TokenGenerator.expires_in`` ...
def generate(self): """ :return: A new token :rtype: str """ random_data = os.urandom(100) hash_gen = hashlib.new("sha512") hash_gen.update(random_data) return hash_gen.hexdigest()[:self.token_length]
def _display_token(self): """ Display token information or redirect to login prompt if none is available. """ if self.token is None: return "301 Moved", "", {"Location": "/login"} return ("200 OK", self.TOKEN_TEMPLATE.format( ...
def _login(self, failed=False): """ Login prompt """ if failed: content = self.LOGIN_TEMPLATE.format(failed_message="Login failed") else: content = self.LOGIN_TEMPLATE.format(failed_message="") return "200 OK", content, {"Content-Type": "text/html"...
def _request_token(self, env): """ Retrieves a new access token from the OAuth2 server. """ params = {} content = env['wsgi.input'].read(int(env['CONTENT_LENGTH'])) post_params = parse_qs(content) # Convert to dict for easier access for param, value in po...
def add_client(self, client_id, client_secret, redirect_uris, authorized_grants=None, authorized_response_types=None): """ Add a client app. :param client_id: Identifier of the client app. :param client_secret: Secret the client app uses for authentication ...
def fetch_by_client_id(self, client_id): """ Retrieve a client by its identifier. :param client_id: Identifier of a client app. :return: An instance of :class:`oauth2.Client`. :raises: ClientNotFoundError """ if client_id not in self.clients: raise C...
def fetch_by_code(self, code): """ Returns an AuthorizationCode. :param code: The authorization code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`AuthCodeNotFound` if no data could be retrieved for given code. ""...
def save_token(self, access_token): """ Stores an access token and additional data in memory. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. """ self.access_tokens[access_token.token] = access_token unique_token_key = self._unique_token_key(ac...
def fetch_by_refresh_token(self, refresh_token): """ Find an access token by its refresh token. :param refresh_token: The refresh token that was assigned to an ``AccessToken``. :return: The :class:`oauth2.datatype.AccessToken`. :raises: :class:`oaut...
def add_grant(self, grant): """ Adds a Grant that the provider should support. :param grant: An instance of a class that extends :class:`oauth2.grant.GrantHandlerFactory` :type grant: oauth2.grant.GrantHandlerFactory """ if hasattr(grant, "expires_i...
def dispatch(self, request, environ): """ Checks which Grant supports the current request and dispatches to it. :param request: The incoming request. :type request: :class:`oauth2.web.Request` :param environ: Dict containing variables of the environment. :type environ: d...
def enable_unique_tokens(self): """ Enable the use of unique access tokens on all grant types that support this option. """ for grant_type in self.grant_types: if hasattr(grant_type, "unique_token"): grant_type.unique_token = True
def header(self, name, default=None): """ Returns the value of the HTTP header identified by `name`. """ wsgi_header = "HTTP_{0}".format(name.upper()) try: return self.env_raw[wsgi_header] except KeyError: return default
def request_body(request): """ Extracts the credentials of a client from the *application/x-www-form-urlencoded* body of a request. Expects the client_id to be the value of the ``client_id`` parameter and the client_secret to be the value of the ``client_secret`` parameter. :param request: The...
def http_basic_auth(request): """ Extracts the credentials of a client using HTTP Basic Auth. Expects the ``client_id`` to be the username and the ``client_secret`` to be the password part of the Authorization header. :param request: The incoming request :type request: oauth2.web.Request ...
def by_identifier(self, request): """ Authenticates a client by its identifier. :param request: The incoming request :type request: oauth2.web.Request :return: The identified client :rtype: oauth2.datatype.Client :raises: :class OAuthInvalidNoRedirectError: ...
def by_identifier_secret(self, request): """ Authenticates a client by its identifier and secret (aka password). :param request: The incoming request :type request: oauth2.web.Request :return: The identified client :rtype: oauth2.datatype.Client :raises OAuthIn...
def expires_in(self): """ Returns the time until the token expires. :return: The remaining time until expiration in seconds or 0 if the token has expired. """ time_left = self.expires_at - int(time.time()) if time_left > 0: return time_left ...
def execute(self, query, *params): """ Executes a query and returns the identifier of the modified row. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: ...
def fetchone(self, query, *args): """ Returns the first result of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: The retrieved row wit...
def fetchall(self, query, *args): """ Returns all results of the given query. :param query: The query to be executed as a `str`. :param params: A `tuple` of parameters that will be replaced for placeholders in the query. :return: A `list` of `tuple`s with ...
def fetch_by_refresh_token(self, refresh_token): """ Retrieves an access token by its refresh token. :param refresh_token: The refresh token of an access token as a `str`. :return: An instance of :class:`oauth2.datatype.AccessToken`. :raises: :class:`oauth2.error.AccessTokenNo...
def fetch_existing_token_of_user(self, client_id, grant_type, user_id): """ Retrieve an access token issued to a client and user for a specific grant. :param client_id: The identifier of a client as a `str`. :param grant_type: The type of grant. :param user_id: The ident...
def save_token(self, access_token): """ Creates a new entry for an access token in the database. :param access_token: An instance of :class:`oauth2.datatype.AccessToken`. :return: `True`. """ access_token_id = self.execute(self.create_acces...
def fetch_by_code(self, code): """ Retrieves an auth code by its code. :param code: The code of an auth code. :return: An instance of :class:`oauth2.datatype.AuthorizationCode`. :raises: :class:`oauth2.error.AuthCodeNotFound` if no auth code could be retrieved...
def save_code(self, authorization_code): """ Creates a new entry of an auth code in the database. :param authorization_code: An instance of :class:`oauth2.datatype.AuthorizationCode`. :return: `True` if everything went fine. """ auth_c...
def fetch_by_client_id(self, client_id): """ Retrieves a client by its identifier. :param client_id: The identifier of a client. :return: An instance of :class:`oauth2.datatype.Client`. :raises: :class:`oauth2.error.ClientError` if no client could be retrieved...
def fetch_by_code(self, code): """ Returns data belonging to an authorization code from memcache or ``None`` if no data was found. See :class:`oauth2.store.AuthCodeStore`. """ code_data = self.mc.get(self._generate_cache_key(code)) if code_data is None: ...
def save_code(self, authorization_code): """ Stores the data belonging to an authorization code token in memcache. See :class:`oauth2.store.AuthCodeStore`. """ key = self._generate_cache_key(authorization_code.code) self.mc.set(key, {"client_id": authorization_code.cli...
def save_token(self, access_token): """ Stores the access token and additional data in memcache. See :class:`oauth2.store.AccessTokenStore`. """ key = self._generate_cache_key(access_token.token) self.mc.set(key, access_token.__dict__) unique_token_key = self._...
def delete_refresh_token(self, refresh_token): """ Deletes a refresh token after use :param refresh_token: The refresh token to delete. """ access_token = self.fetch_by_refresh_token(refresh_token) self.mc.delete(self._generate_cache_key(access_token.token)) self....
def encode_scopes(scopes, use_quote=False): """ Creates a string out of a list of scopes. :param scopes: A list of scopes :param use_quote: Boolean flag indicating whether the string should be quoted :return: Scopes as a string """ scopes_as_string = Scope.separator.join(scopes) if use...
def json_error_response(error, response, status_code=400): """ Formats an error as a response containing a JSON body. """ msg = {"error": error.error, "error_description": error.explanation} response.status_code = status_code response.add_header("Content-Type", "application/json") response....
def json_success_response(data, response): """ Formats the response of a successful token request as JSON. Also adds default headers and status code. """ response.body = json.dumps(data) response.status_code = 200 response.add_header("Content-Type", "application/json") response.add_hea...
def compare(self, previous_scopes): """ Compares the scopes read from request with previously issued scopes. :param previous_scopes: A list of scopes. :return: ``True`` """ for scope in self.scopes: if scope not in previous_scopes: raise OAuth...
def parse(self, request, source): """ Parses scope value in given request. Expects the value of the "scope" parameter in request to be a string where each requested scope is separated by a white space:: # One scope requested "profile_read" # Multipl...
def read_validate_params(self, request): """ Reads and validates data in an incoming request as required by the Authorization Request of the Authorization Code Grant and the Implicit Grant. """ self.client = self.client_authenticator.by_identifier(request) respon...
def authorize(self, request, response, environ, scopes): """ Controls all steps to authorize a request by a user. :param request: The incoming :class:`oauth2.web.Request` :param response: The :class:`oauth2.web.Response` that will be returned eventually ...
def process(self, request, response, environ): """ Generates a new authorization token. A form to authorize the access of the application can be displayed with the help of `oauth2.web.SiteAdapter`. """ data = self.authorize(request, response, environ, ...
def handle_error(self, error, response): """ Redirects the client in case an error in the auth process occurred. """ query_params = {"error": error.error} query = urlencode(query_params) location = "%s?%s" % (self.client.redirect_uri, query) response.status_cod...
def process(self, request, response, environ): """ Generates a new access token and returns it. Returns the access token and the type of the token as JSON. Calls `oauth2.store.AccessTokenStore` to persist the token. """ token_data = self.create_token( client...
def process(self, request, response, environ): """ Takes the incoming request, asks the concrete SiteAdapter to validate it and issues a new access token that is returned to the client on successful validation. """ try: data = self.site_adapter.authenticate(re...
def read_validate_params(self, request): """ Checks if all incoming parameters meet the expected values. """ self.client = self.client_authenticator.by_identifier_secret(request) self.password = request.post_param("password") self.username = request.post_param("username"...
def process(self, request, response, environ): """ Create a new access token. :param request: The incoming :class:`oauth2.web.Request`. :param response: The :class:`oauth2.web.Response` that will be returned to the client. :param environ: A ``dict`` cont...
def read_validate_params(self, request): """ Validate the incoming request. :param request: The incoming :class:`oauth2.web.Request`. :return: Returns ``True`` if data is valid. :raises: :class:`oauth2.error.OAuthInvalidError` """ self.refresh_token = request....
def value_for_keypath(obj, path): """Get value from walking key path with start object obj. """ val = obj for part in path.split('.'): match = re.match(list_index_re, part) if match is not None: val = _extract(val, match.group(1)) if not isinstance(val, list) and ...
def set_value_for_keypath(obj, path, new_value, preserve_child = False): """Set attribute value new_value at key path of start object obj. """ parts = path.split('.') last_part = len(parts) - 1 dst = obj for i, part in enumerate(parts): match = re.match(list_index_re, part) if ma...
def view_for_image_named(image_name): """Create an ImageView for the given image.""" image = resource.get_image(image_name) if not image: return None return ImageView(pygame.Rect(0, 0, 0, 0), image)
def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" tarball = download_setuptools() _install(tarball, _build_install_args(argv))
def fill_gradient(surface, color, gradient, rect=None, vertical=True, forward=True): """Fill a surface with a linear gradient pattern. color starting color gradient final color rect area to fill; default is surface's rect vertical True=verti...
def shrink_wrap(self): """Tightly bound the current text respecting current padding.""" self.frame.size = (self.text_size[0] + self.padding[0] * 2, self.text_size[1] + self.padding[1] * 2)
def layout(self): """Call to have the view layout itself. Subclasses should invoke this after laying out child views and/or updating its own frame. """ if self.shadowed: shadow_size = theme.current.shadow_size shadowed_frame_size = (self.frame.w + shadow_...
def stylize(self): """Apply theme style attributes to this instance and its children. This also causes a relayout to occur so that any changes in padding or other stylistic attributes may be handled. """ # do children first in case parent needs to override their style fo...
def draw(self): """Do not call directly.""" if self.hidden: return False if self.background_color is not None: render.fillrect(self.surface, self.background_color, rect=pygame.Rect((0, 0), self.frame.size)) for child in self.children...
def get_border_widths(self): """Return border width for each side top, left, bottom, right.""" if type(self.border_widths) is int: # uniform size return [self.border_widths] * 4 return self.border_widths
def hit(self, pt): """Find the view (self, child, or None) under the point `pt`.""" if self.hidden or not self._enabled: return None if not self.frame.collidepoint(pt): return None local_pt = (pt[0] - self.frame.topleft[0], pt[1] - self.fram...
def bring_to_front(self): """TODO: explain depth sorting""" if self.parent is not None: ch = self.parent.children index = ch.index(self) ch[-1], ch[index] = ch[index], ch[-1]
def use_theme(theme): """Make the given theme current. There are two included themes: light_theme, dark_theme. """ global current current = theme import scene if scene.current is not None: scene.current.stylize()
def set(self, class_name, state, key, value): """Set a single style value for a view class and state. class_name The name of the class to be styled; do not include the package name; e.g. 'Button'. state The name of the state to be stylized. One of the ...
def get_dict_for_class(self, class_name, state=None, base_name='View'): """The style dict for a given class and state. This collects the style attributes from parent classes and the class of the given object and gives precedence to values thereof to the children. The state attr...
def get_dict(self, obj, state=None, base_name='View'): """The style dict for a view instance. """ return self.get_dict_for_class(class_name=obj.__class__, state=obj.state, base_name=base_name)
def get_value(self, class_name, attr, default_value=None, state='normal', base_name='View'): """Get a single style attribute value for the given class. """ styles = self.get_dict_for_class(class_name, state, base_name) try: return styles[attr] excep...
def serialize(self, queryset, **options): """ Serialize a queryset. """ self.options = options self.stream = options.pop("stream", six.StringIO()) self.selected_fields = options.pop("fields", None) self.use_natural_keys = options.pop("use_natural_keys", False) ...
def current(self, fields=None): """Returns dict of current values for all tracked fields""" if fields is None: fields = self.fields return dict((f, self.get_field_value(f)) for f in fields)
def instantiate_object_id_field(object_id_class_or_tuple=models.TextField): """ Instantiates and returns a model field for FieldHistory.object_id. object_id_class_or_tuple may be either a Django model field class or a tuple of (model_field, kwargs), where kwargs is a dict passed to model_field's co...
def has_expired(self, lifetime, now=None): """Report if the session key has expired. :param lifetime: A :class:`datetime.timedelta` that specifies the maximum age this :class:`SessionID` should be checked against. :param now: If specified, use t...
def unserialize(cls, string): """Unserializes from a string. :param string: A string created by :meth:`serialize`. """ id_s, created_s = string.split('_') return cls(int(id_s, 16), datetime.utcfromtimestamp(int(created_s, 16)))
def destroy(self): """Destroys a session completely, by deleting all keys and removing it from the internal store immediately. This allows removing a session for security reasons, e.g. a login stored in a session will cease to exist if the session is destroyed. """ for k...
def regenerate(self): """Generate a new session id for this session. To avoid vulnerabilities through `session fixation attacks <http://en.wikipedia.org/wiki/Session_fixation>`_, this function can be called after an action like a login has taken place. The session will be copied...
def cleanup_sessions(self, app=None): """Removes all expired session from the store. Periodically, this function can be called to remove sessions from the backend store that have expired, as they are not removed automatically unless the backend supports time-to-live and has been ...
def init_app(self, app, session_kvstore=None): """Initialize application and KVSession. This will replace the session management of the application with Flask-KVSession's. :param app: The :class:`~flask.Flask` app to be initialized.""" app.config.setdefault('SESSION_KEY_BITS', ...
def transfer_config_dict(soap_object, data_dict): """ This is a utility function used in the certification modules to transfer the data dicts above to SOAP objects. This avoids repetition and allows us to store all of our variable configuration here rather than in each certification script. """ ...
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.createPickup( ...
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.getPickupAvailabil...
def _prepare_wsdl_objects(self): """ This is the data that will be used to create your shipment. Create the data structure and get it ready for the WSDL request. """ # This is the primary data structure for processShipment requests. self.RequestedShipment = self.client.f...
def _assemble_and_send_validation_request(self): """ Fires off the Fedex shipment validation request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_validation_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off ...
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.processSh...
def add_package(self, package_item): """ Adds a package to the ship request. @type package_item: WSDL object, type of RequestedPackageLineItem WSDL object. @keyword package_item: A RequestedPackageLineItem, created by calling create_wsdl_object_of_type('...
def _prepare_wsdl_objects(self): """ Preps the WSDL data structures for the user. """ self.DeletionControlType = self.client.factory.create('DeletionControlType') self.TrackingId = self.client.factory.create('TrackingId') self.TrackingId.TrackingIdType = self.client.fact...
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ client = self.client # Fire off the query. return c...
def _prepare_wsdl_objects(self): """ This is the data that will be used to create your shipment. Create the data structure and get it ready for the WSDL request. """ self.UploadDocumentsRequest = self.client.factory.create('UploadDocumentsRequest') ...
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.clien...
def __set_web_authentication_detail(self): """ Sets up the WebAuthenticationDetail node. This is required for all requests. """ # Start of the authentication stuff. web_authentication_credential = self.client.factory.create('WebAuthenticationCredential') web_auth...
def __set_client_detail(self, *args, **kwargs): """ Sets up the ClientDetail node, which is required for all shipping related requests. """ client_detail = self.client.factory.create('ClientDetail') client_detail.AccountNumber = self.config_obj.account_number cli...
def __set_transaction_detail(self, *args, **kwargs): """ Checks kwargs for 'customer_transaction_id' and sets it if present. """ customer_transaction_id = kwargs.get('customer_transaction_id', None) if customer_transaction_id: transaction_detail = self.client.factory...
def __set_version_id(self): """ Pulles the versioning info for the request from the child request. """ version_id = self.client.factory.create('VersionId') version_id.ServiceId = self._version_info['service_id'] version_id.Major = self._version_info['major'] vers...
def __check_response_for_fedex_error(self): """ This checks the response for general Fedex errors that aren't related to any one WSDL. """ if self.response.HighestSeverity == "FAILURE": for notification in self.response.Notifications: if notification....