_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q42300
instantiate_from_config
train
def instantiate_from_config(cfg): """Instantiate data types from config""" for h in cfg: if h.get("type") in data_types: raise KeyError("Data type '%s' already exists" % h) data_types[h.get("type")] = DataType(h)
python
{ "resource": "" }
q42301
BaseCanvasAPI.extract_data_from_response
train
def extract_data_from_response(self, response, data_key=None): """Given a response and an optional data_key should return a dictionary of data returned as part of the response.""" response_json_data = response.json() # Seems to be two types of response, a dict with keys and then lists of data...
python
{ "resource": "" }
q42302
BaseCanvasAPI.extract_pagination_links
train
def extract_pagination_links(self, response): '''Given a wrapped_response from a Canvas API endpoint, extract the pagination links from the response headers''' try: link_header = response.headers['Link'] except KeyError: logger.warn('Unable to find the Link ...
python
{ "resource": "" }
q42303
BaseCanvasAPI.generic_request
train
def generic_request(self, method, uri, all_pages=False, data_key=None, no_data=False, do_not_process=False, force_urlencode_data=False, data=None, ...
python
{ "resource": "" }
q42304
BaseCanvasAPI._validate_iso8601_string
train
def _validate_iso8601_string(self, value): """Return the value or raise a ValueError if it is not a string in ISO8601 format.""" ISO8601_REGEX = r'(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})([+-](\d{2})\:(\d{2})|Z)' if re.match(ISO8601_REGEX, value): return value e...
python
{ "resource": "" }
q42305
create_database
train
def create_database(dbpath, schema='', overwrite=True): """ Create a new database at the given dbpath Parameters ---------- dbpath: str The full path for the new database, including the filename and .db file extension. schema: str The path to the .sql schema for the database ...
python
{ "resource": "" }
q42306
adapt_array
train
def adapt_array(arr): """ Adapts a Numpy array into an ARRAY string to put into the database. Parameters ---------- arr: array The Numpy array to be adapted into an ARRAY type that can be inserted into a SQL file. Returns ------- ARRAY The adapted array object ...
python
{ "resource": "" }
q42307
convert_array
train
def convert_array(array): """ Converts an ARRAY string stored in the database back into a Numpy array. Parameters ---------- array: ARRAY The array object to be converted back into a Numpy array. Returns ------- array The converted Numpy array. """ out = io...
python
{ "resource": "" }
q42308
convert_image
train
def convert_image(File, verbose=False): """ Converts a IMAGE data type stored in the database into a data cube Parameters ---------- File: str The URL or filepath of the file to be converted into arrays. verbose: bool Whether or not to display some diagnostic information (Defaul...
python
{ "resource": "" }
q42309
pprint
train
def pprint(data, names='', title='', formats={}): """ Prints tables with a bit of formatting Parameters ---------- data: (sequence, dict, table) The data to print in the table names: sequence The column names title: str (optional) The title of the table formats: ...
python
{ "resource": "" }
q42310
Database.add_changelog
train
def add_changelog(self, user="", mod_tables="", user_desc=""): """ Add an entry to the changelog table. This should be run when changes or edits are done to the database. Parameters ---------- user: str Name of the person who made the edits mod_tables: str ...
python
{ "resource": "" }
q42311
Database.close
train
def close(self, silent=False): """ Close the database and ask to save and delete the file Parameters ---------- silent: bool Close quietly without saving or deleting (Default: False). """ if not silent: saveme = get_input("Save database co...
python
{ "resource": "" }
q42312
Database.get_bibtex
train
def get_bibtex(self, id, fetch=False, table='publications'): """ Grab bibtex entry from NASA ADS Parameters ---------- id: int or str The id or shortname from the PUBLICATIONS table to search fetch: bool Whether or not to return the bibtex string ...
python
{ "resource": "" }
q42313
Database.info
train
def info(self): """ Prints out information for the loaded database, namely the available tables and the number of entries for each. """ t = self.query("SELECT * FROM sqlite_master WHERE type='table'", fmt='table') all_tables = t['name'].tolist() print('\nDatabase path: {}...
python
{ "resource": "" }
q42314
Database._lowest_rowids
train
def _lowest_rowids(self, table, limit): """ Gets the lowest available row ids for table insertion. Keeps things tidy! Parameters ---------- table: str The name of the table being modified limit: int The number of row ids needed Returns ...
python
{ "resource": "" }
q42315
Database.output_spectrum
train
def output_spectrum(self, spectrum, filepath, header={}): """ Prints a file of the given spectrum to an ascii file with specified filepath. Parameters ---------- spectrum: int, sequence The id from the SPECTRA table or a [w,f,e] sequence filepath: str ...
python
{ "resource": "" }
q42316
Database.schema
train
def schema(self, table): """ Print the table schema Parameters ---------- table: str The table name """ try: pprint(self.query("PRAGMA table_info({})".format(table), fmt='table')) except ValueError: print('Table {} not f...
python
{ "resource": "" }
q42317
Database.snapshot
train
def snapshot(self, name_db='export.db', version=1.0): """ Function to generate a snapshot of the database by version number. Parameters ---------- name_db: string Name of the new database (Default: export.db) version: float Version number to expor...
python
{ "resource": "" }
q42318
read
train
def read(path): """Read a secret from Vault REST endpoint""" url = '{}/{}/{}'.format(settings.VAULT_BASE_URL.rstrip('/'), settings.VAULT_BASE_SECRET_PATH.strip('/'), path.lstrip('/')) headers = {'X-Vault-Token': settings.VAULT_ACCESS_TOKEN} resp =...
python
{ "resource": "" }
q42319
RabaConnection.getIndexes
train
def getIndexes(self, rabaOnly = True) : "returns a list of all indexes in the sql database. rabaOnly returns only the indexes created by raba" sql = "SELECT * FROM sqlite_master WHERE type='index'" cur = self.execute(sql) l = [] for n in cur : if rabaOnly : if n[1].lower().find('raba') == 0 : l.ap...
python
{ "resource": "" }
q42320
RabaConnection.flushIndexes
train
def flushIndexes(self) : "drops all indexes created by Raba" for n in self.getIndexes(rabaOnly = True) : self.dropIndexByName(n[1])
python
{ "resource": "" }
q42321
RabaConnection.enableStats
train
def enableStats(self, bol, logQueries = False) : "If bol == True, Raba will keep a count of every query time performed, logQueries == True it will also keep a record of all the queries " self._enableStats = bol self._logQueries = logQueries if bol : self._enableStats = True self.eraseStats() self.start...
python
{ "resource": "" }
q42322
RabaConnection.execute
train
def execute(self, sql, values = ()) : "executes an sql command for you or appends it to the current transacations. returns a cursor" sql = sql.strip() self._debugActions(sql, values) cur = self.connection.cursor() cur.execute(sql, values) return cur
python
{ "resource": "" }
q42323
RabaConnection.initateSave
train
def initateSave(self, obj) : """Tries to initiates a save sessions. Each object can only be saved once during a session. The session begins when a raba object initates it and ends when this object and all it's dependencies have been saved""" if self.saveIniator != None : return False self.saveIniator = obj ...
python
{ "resource": "" }
q42324
RabaConnection.freeSave
train
def freeSave(self, obj) : """THIS IS WHERE COMMITS TAKE PLACE! Ends a saving session, only the initiator can end a session. The commit is performed at the end of the session""" if self.saveIniator is obj and not self.inTransaction : self.saveIniator = None self.savedObject = set() self.connection.commit(...
python
{ "resource": "" }
q42325
RabaConnection.registerSave
train
def registerSave(self, obj) : """Each object can only be save donce during a session, returns False if the object has already been saved. True otherwise""" if obj._runtimeId in self.savedObject : return False self.savedObject.add(obj._runtimeId) return True
python
{ "resource": "" }
q42326
RabaConnection.getLastRabaId
train
def getLastRabaId(self, cls) : """keep track all loaded raba classes""" self.loadedRabaClasses[cls.__name__] = cls sql = 'SELECT MAX(raba_id) from %s LIMIT 1' % (cls.__name__) cur = self.execute(sql) res = cur.fetchone() try : return int(res[0])+1 except TypeError: return 0
python
{ "resource": "" }
q42327
RabaConnection.createTable
train
def createTable(self, tableName, strFields) : 'creates a table and resturns the ursor, if the table already exists returns None' if not self.tableExits(tableName) : sql = 'CREATE TABLE %s ( %s)' % (tableName, strFields) self.execute(sql) self.tables.add(tableName) return True return False
python
{ "resource": "" }
q42328
RabaConnection.dropColumnsFromRabaObjTable
train
def dropColumnsFromRabaObjTable(self, name, lstFieldsToKeep) : "Removes columns from a RabaObj table. lstFieldsToKeep should not contain raba_id or json fileds" if len(lstFieldsToKeep) == 0 : raise ValueError("There are no fields to keep") cpy = name+'_copy' sqlFiledsStr = ', '.join(lstFieldsToKeep) self....
python
{ "resource": "" }
q42329
suser.get_likes
train
def get_likes(self, offset=0, limit=50): """ Get user's likes. """ response = self.client.get( self.client.USER_LIKES % (self.name, offset, limit)) return self._parse_response(response, strack)
python
{ "resource": "" }
q42330
suser.get_tracks
train
def get_tracks(self, offset=0, limit=50): """ Get user's tracks. """ response = self.client.get( self.client.USER_TRACKS % (self.name, offset, limit)) return self._parse_response(response, strack)
python
{ "resource": "" }
q42331
suser.get_playlists
train
def get_playlists(self, offset=0, limit=50): """ Get user's playlists. """ response = self.client.get( self.client.USER_PLAYLISTS % (self.name, offset, limit)) return self._parse_response(response, splaylist) return playlists
python
{ "resource": "" }
q42332
suser._parse_response
train
def _parse_response(self, response, target_object=strack): """ Generic response parser method """ objects = json.loads(response.read().decode("utf-8")) list = [] for obj in objects: list.append(target_object(obj, client=self.client)) return list
python
{ "resource": "" }
q42333
SimpleBayes.calculate_category_probability
train
def calculate_category_probability(self): """ Caches the individual probabilities for each category """ total_tally = 0.0 probs = {} for category, bayes_category in \ self.categories.get_categories().items(): count = bayes_category.get_tally() ...
python
{ "resource": "" }
q42334
SimpleBayes.train
train
def train(self, category, text): """ Trains a category with a sample of text :param category: the name of the category we want to train :type category: str :param text: the text we want to train the category with :type text: str """ try: bayes...
python
{ "resource": "" }
q42335
SimpleBayes.untrain
train
def untrain(self, category, text): """ Untrains a category with a sample of text :param category: the name of the category we want to train :type category: str :param text: the text we want to untrain the category with :type text: str """ try: ...
python
{ "resource": "" }
q42336
SimpleBayes.classify
train
def classify(self, text): """ Chooses the highest scoring category for a sample of text :param text: sample text to classify :type text: str :return: the "winning" category :rtype: str """ score = self.score(text) if not score: return ...
python
{ "resource": "" }
q42337
SimpleBayes.score
train
def score(self, text): """ Scores a sample of text :param text: sample text to score :type text: str :return: dict of scores per category :rtype: dict """ occurs = self.count_token_occurrences(self.tokenizer(text)) scores = {} for category...
python
{ "resource": "" }
q42338
SimpleBayes.tally
train
def tally(self, category): """ Gets the tally for a requested category :param category: The category we want a tally for :type category: str :return: tally for a given category :rtype: int """ try: bayes_category = self.categories.get_category...
python
{ "resource": "" }
q42339
SimpleBayes.get_cache_location
train
def get_cache_location(self): """ Gets the location of the cache file :return: the location of the cache file :rtype: string """ filename = self.cache_path if \ self.cache_path[-1:] == '/' else \ self.cache_path + '/' filename += self.cach...
python
{ "resource": "" }
q42340
SimpleBayes.cache_persist
train
def cache_persist(self): """ Saves the current trained data to the cache. This is initiated by the program using this module """ filename = self.get_cache_location() pickle.dump(self.categories, open(filename, 'wb'))
python
{ "resource": "" }
q42341
SimpleBayes.cache_train
train
def cache_train(self): """ Loads the data for this classifier from a cache file :return: whether or not we were successful :rtype: bool """ filename = self.get_cache_location() if not os.path.exists(filename): return False categories = pickl...
python
{ "resource": "" }
q42342
ContributorRole.create_feature_type_rates
train
def create_feature_type_rates(self, created=False): """ If the role is being created we want to populate a rate for all existing feature_types. """ if created: for feature_type in FeatureType.objects.all(): FeatureTypeRate.objects.create(role=self, feature_typ...
python
{ "resource": "" }
q42343
Handler.addToService
train
def addToService(self, service, namespace=None, seperator='.'): """ Add this Handler's exported methods to an RPC Service instance. """ if namespace is None: namespace = [] if isinstance(namespace, basestring): namespace = [namespace] for n, m in ...
python
{ "resource": "" }
q42344
print_progress_bar
train
def print_progress_bar(text, done, total, width): """ Print progress bar. """ if total > 0: n = int(float(width) * float(done) / float(total)) sys.stdout.write("\r{0} [{1}{2}] ({3}/{4})".format(text, '#' * n, ' ' * (width - n), done, total)) sys.stdout.flush()
python
{ "resource": "" }
q42345
fetch_modules
train
def fetch_modules(config, relative_path, download_directory): """ Assemble modules which will be included in CMakeLists.txt. """ from collections import Iterable, namedtuple, defaultdict from autocmake.extract import extract_list, to_d, to_l from autocmake.parse_rst import parse_cmake_module...
python
{ "resource": "" }
q42346
fetch_url
train
def fetch_url(src, dst): """ Fetch file from URL src and save it to dst. """ # we do not use the nicer sys.version_info.major # for compatibility with Python < 2.7 if sys.version_info[0] > 2: import urllib.request class URLopener(urllib.request.FancyURLopener): def h...
python
{ "resource": "" }
q42347
PollSubmissionsAPI.get_single_poll_submission
train
def get_single_poll_submission(self, id, poll_id, poll_session_id): """ Get a single poll submission. Returns the poll submission with the given id """ path = {} data = {} params = {} # REQUIRED - PATH - poll_id """ID""" path[...
python
{ "resource": "" }
q42348
PollSubmissionsAPI.create_single_poll_submission
train
def create_single_poll_submission(self, poll_id, poll_session_id, poll_submissions_poll_choice_id): """ Create a single poll submission. Create a new poll submission for this poll session """ path = {} data = {} params = {} # REQUIRED - PATH - ...
python
{ "resource": "" }
q42349
HasPermissionOrIsAuthor.has_object_permission
train
def has_object_permission(self, request, view, obj): """determines if requesting user has permissions for the object :param request: WSGI request object - where we get the user from :param view: the view calling for permission :param obj: the object in question :return: `bool` ...
python
{ "resource": "" }
q42350
CanEditCmsNotifications.has_permission
train
def has_permission(self, request, view): """If method is GET, user can access, if method is PUT or POST user must be a superuser. """ has_permission = False if request.method == "GET" \ or request.method in ["PUT", "POST", "DELETE"] \ and request.user and ...
python
{ "resource": "" }
q42351
Api.bind
train
def bind(self, app): """Bind API to Muffin.""" self.parent = app app.add_subapp(self.prefix, self.app)
python
{ "resource": "" }
q42352
Api.register
train
def register(self, *paths, methods=None, name=None): """Register handler to the API.""" if isinstance(methods, str): methods = [methods] def wrapper(handler): if isinstance(handler, (FunctionType, MethodType)): handler = RESTHandler.from_view(handler, *(...
python
{ "resource": "" }
q42353
Api.swagger_schema
train
def swagger_schema(self, request): """Render API Schema.""" if self.parent is None: return {} spec = APISpec( self.parent.name, self.parent.cfg.get('VERSION', ''), plugins=['apispec.ext.marshmallow'], basePatch=self.prefix ) for paths, handle...
python
{ "resource": "" }
q42354
update_pzone
train
def update_pzone(**kwargs): """Update pzone data in the DB""" pzone = PZone.objects.get(**kwargs) # get the data and loop through operate_on, applying them if necessary when = timezone.now() data = pzone.data for operation in pzone.operations.filter(when__lte=when, applied=False): data...
python
{ "resource": "" }
q42355
PZoneManager.operate_on
train
def operate_on(self, when=None, apply=False, **kwargs): """Do something with operate_on. If apply is True, all transactions will be applied and saved via celery task.""" # get pzone based on id pzone = self.get(**kwargs) # cache the current time now = timezone.now() ...
python
{ "resource": "" }
q42356
PZoneManager.preview
train
def preview(self, when=timezone.now(), **kwargs): """Preview transactions, but don't actually save changes to list.""" return self.operate_on(when=when, apply=False, **kwargs)
python
{ "resource": "" }
q42357
strack.get_download_link
train
def get_download_link(self): """ Get direct download link with soudcloud's redirect system. """ url = None if not self.get("downloadable"): try: url = self.client.get_location( self.client.STREAM_URL % self.get("id")) except serror as e...
python
{ "resource": "" }
q42358
strack.get_file_extension
train
def get_file_extension(self, filepath): """ This method check mimetype to define file extension. If it can't, it use original-format metadata. """ mtype = magic.from_file(filepath, mime=True) if type(mtype) == bytes: mtype = mtype.decode("utf-8") if m...
python
{ "resource": "" }
q42359
strack.gen_localdir
train
def gen_localdir(self, localdir): """ Generate local directory where track will be saved. Create it if not exists. """ directory = "{0}/{1}/".format(localdir, self.get("username")) if not os.path.exists(directory): os.makedirs(directory) return directo...
python
{ "resource": "" }
q42360
strack.track_exists
train
def track_exists(self, localdir): """ Check if track exists in local directory. """ path = glob.glob(self.gen_localdir(localdir) + self.gen_filename() + "*") if len(path) > 0 and os.path.getsize(path[0]) > 0: return True return False
python
{ "resource": "" }
q42361
strack.get_ignored_tracks
train
def get_ignored_tracks(self, localdir): """ Get ignored tracks list. """ ignore_file = "%s/.ignore" % localdir list = [] if os.path.exists(ignore_file): f = open(ignore_file) ignored = f.readlines() f.close() for i in ignored: ...
python
{ "resource": "" }
q42362
strack.download
train
def download(self, localdir, max_retry): """ Download a track in local directory. """ local_file = self.gen_localdir(localdir) + self.gen_filename() if self.track_exists(localdir): print("Track {0} already downloaded, skipping!".format( self.get("id"))) r...
python
{ "resource": "" }
q42363
strack.process_tags
train
def process_tags(self, tag=None): """Process ID3 Tags for mp3 files.""" if self.downloaded is False: raise serror("Track not downloaded, can't process tags..") filetype = magic.from_file(self.filepath, mime=True) if filetype != "audio/mpeg": raise serror("Cannot p...
python
{ "resource": "" }
q42364
strack.convert
train
def convert(self): """Convert file in mp3 format.""" if self.downloaded is False: raise serror("Track not downloaded, can't convert file..") filetype = magic.from_file(self.filepath, mime=True) if filetype == "audio/mpeg": print("File is already in mp3 format. Ski...
python
{ "resource": "" }
q42365
strack.download_artwork
train
def download_artwork(self, localdir, max_retry): """ Download track's artwork and return file path. Artwork's path is saved in track's metadata as 'artwork-path' key. """ if self.get("artwork-url") == "None": self.metadata["artwork-path"] = None return Non...
python
{ "resource": "" }
q42366
strack._progress_hook
train
def _progress_hook(self, blocknum, blocksize, totalsize): """ Progress hook for urlretrieve. """ read = blocknum * blocksize if totalsize > 0: percent = read * 1e2 / totalsize s = "\r%d%% %*d / %d" % ( percent, len(str(totalsize)), read, totalsize) ...
python
{ "resource": "" }
q42367
stag.load_id3
train
def load_id3(self, track): """ Load id3 tags from strack metadata """ if not isinstance(track, strack): raise TypeError('strack object required') timestamp = calendar.timegm(parse(track.get("created-at")).timetuple()) self.mapper[TIT1] = TIT1(text=track.get("description")) ...
python
{ "resource": "" }
q42368
stag.write_id3
train
def write_id3(self, filename): """ Write id3 tags """ if not os.path.exists(filename): raise ValueError("File doesn't exists.") self.mapper.write(filename)
python
{ "resource": "" }
q42369
SpriteTexturizer.from_images
train
def from_images(cls, images, weights=None, filter=None, wrap=None, aspect_adjust_width=False, aspect_adjust_height=False): """Create a SpriteTexturizer from a sequence of Pyglet images. Note all the images must be able to fit into a single OpenGL texture, so their combined size should typically be less than 10...
python
{ "resource": "" }
q42370
parse_querystring
train
def parse_querystring(querystring): """ Return parsed querystring in dict """ if querystring is None or len(querystring) == 0: return {} qs_dict = parse.parse_qs(querystring, keep_blank_values=True) for key in qs_dict: if len(qs_dict[key]) != 1: continue qs_d...
python
{ "resource": "" }
q42371
Message.to_json
train
def to_json(self, pretty=True): """ to_json will call to_dict then dumps into json format """ data_dict = self.to_dict() if pretty: return json.dumps( data_dict, sort_keys=True, indent=2) return json.dumps(data_dict, sort_keys=True)
python
{ "resource": "" }
q42372
Message.to_dict
train
def to_dict(self): """ to_dict will clean all protected and private properties """ return dict( (k, self.__dict__[k]) for k in self.__dict__ if k.find("_") != 0)
python
{ "resource": "" }
q42373
Message.match
train
def match(self, route): """ Match input route and return new Message instance with parsed content """ _resource = trim_resource(self.resource) self.method = self.method.lower() resource_match = route.resource_regex.search(_resource) if resource_match is No...
python
{ "resource": "" }
q42374
Message.get_message_type
train
def get_message_type(message): """ Return message's type """ for msg_type in MessageType.FIELDS: if Message.is_type(msg_type, message): return msg_type return MessageType.UNKNOWN
python
{ "resource": "" }
q42375
Message.is_type
train
def is_type(msg_type, msg): """ Return message's type is or not """ for prop in MessageType.FIELDS[msg_type]["must"]: if msg.get(prop, False) is False: return False for prop in MessageType.FIELDS[msg_type]["prohibit"]: if msg.get(prop, Fals...
python
{ "resource": "" }
q42376
JSONRPCService.add
train
def add(self, f, name=None, types=None, required=None): """ Adds a new method to the jsonrpc service. Arguments: f -- the remote function name -- name of the method in the jsonrpc service types -- list or dictionary of the types of accepted arguments required -- ...
python
{ "resource": "" }
q42377
JSONRPCService.stopServing
train
def stopServing(self, exception=None): """ Returns a deferred that will fire immediately if there are no pending requests, otherwise when the last request is removed from self.pending. """ if exception is None: exception = ServiceUnavailableError self....
python
{ "resource": "" }
q42378
JSONRPCService.call
train
def call(self, jsondata): """ Calls jsonrpc service's method and returns its return value in a JSON string or None if there is none. Arguments: jsondata -- remote method call in jsonrpc format """ result = yield self.call_py(jsondata) if result is None: ...
python
{ "resource": "" }
q42379
JSONRPCService.call_py
train
def call_py(self, jsondata): """ Calls jsonrpc service's method and returns its return value in python object format or None if there is none. This method is same as call() except the return value is a python object instead of JSON string. This method is mainly only useful for ...
python
{ "resource": "" }
q42380
JSONRPCService._get_err
train
def _get_err(self, e, id=None, jsonrpc=DEFAULT_JSONRPC): """ Returns jsonrpc error message. """ # Do not respond to notifications when the request is valid. if not id \ and not isinstance(e, ParseError) \ and not isinstance(e, InvalidRequestError):...
python
{ "resource": "" }
q42381
JSONRPCService._man_args
train
def _man_args(self, f): """ Returns number of mandatory arguments required by given function. """ argcount = f.func_code.co_argcount # account for "self" getting passed to class instance methods if isinstance(f, types.MethodType): argcount -= 1 if f....
python
{ "resource": "" }
q42382
JSONRPCService._max_args
train
def _max_args(self, f): """ Returns maximum number of arguments accepted by given function. """ if f.func_defaults is None: return f.func_code.co_argcount return f.func_code.co_argcount + len(f.func_defaults)
python
{ "resource": "" }
q42383
JSONRPCService._get_id
train
def _get_id(self, rdata): """ Returns jsonrpc request's id value or None if there is none. InvalidRequestError will be raised if the id value has invalid type. """ if 'id' in rdata: if isinstance(rdata['id'], basestring) or \ isinstance(rdata['id'...
python
{ "resource": "" }
q42384
JSONRPCService._get_method
train
def _get_method(self, rdata): """ Returns jsonrpc request's method value. InvalidRequestError will be raised if it's missing or is wrong type. MethodNotFoundError will be raised if a method with given method name does not exist. """ if 'method' in rdata: ...
python
{ "resource": "" }
q42385
JSONRPCService._get_params
train
def _get_params(self, rdata): """ Returns a list of jsonrpc request's method parameters. """ if 'params' in rdata: if isinstance(rdata['params'], dict) \ or isinstance(rdata['params'], list) \ or rdata['params'] is None: ...
python
{ "resource": "" }
q42386
JSONRPCService._fill_request
train
def _fill_request(self, request, rdata): """Fills request with data from the jsonrpc call.""" if not isinstance(rdata, dict): raise InvalidRequestError request['jsonrpc'] = self._get_jsonrpc(rdata) request['id'] = self._get_id(rdata) request['method'] = self._get_met...
python
{ "resource": "" }
q42387
JSONRPCService._call_method
train
def _call_method(self, request): """Calls given method with given params and returns it value.""" method = self.method_data[request['method']]['method'] params = request['params'] result = None try: if isinstance(params, list): # Does it have enough ar...
python
{ "resource": "" }
q42388
JSONRPCService._handle_request
train
def _handle_request(self, request): """Handles given request and returns its response.""" if 'types' in self.method_data[request['method']]: self._validate_params_types(request['method'], request['params']) if self.serve_exception: raise self.serve_exception() d ...
python
{ "resource": "" }
q42389
JSONRPCService._validate_params_types
train
def _validate_params_types(self, method, params): """ Validates request's parameter types. """ if isinstance(params, list): if not isinstance(self.method_data[method]['types'], list): raise InvalidParamsError( 'expected keyword params, not ...
python
{ "resource": "" }
q42390
JSONRPCClientService.startService
train
def startService(self): """ Start the service and connect the JSONRPCClientFactory. """ self.clientFactory.connect().addErrback( log.err, 'error starting the JSON-RPC client service %r' % (self,)) service.Service.startService(self)
python
{ "resource": "" }
q42391
JSONRPCClientService.callRemote
train
def callRemote(self, *a, **kw): """ Make a callRemote request of the JSONRPCClientFactory. """ if not self.running: return defer.fail(ServiceStopped()) return self.clientFactory.callRemote(*a, **kw)
python
{ "resource": "" }
q42392
JSONRPCError.dumps
train
def dumps(self): """Return the Exception data in a format for JSON-RPC.""" error = {'code': self.code, 'message': str(self.message)} if self.data is not None: error['data'] = self.data return error
python
{ "resource": "" }
q42393
ReadTuple.stringize
train
def stringize( self, rnf_profile=RnfProfile(), ): """Create RNF representation of this read. Args: read_tuple_id_width (int): Maximal expected string length of read tuple ID. genome_id_width (int): Maximal expected string length of genome ID. chr_id_width (int): Maximal expected ...
python
{ "resource": "" }
q42394
ReadTuple.destringize
train
def destringize(self, string): """Get RNF values for this read from its textual representation and save them into this object. Args: string(str): Textual representation of a read. Raises: ValueError """ # todo: assert -- starting with (, ending with ) # (prefix,read_tuple_id,se...
python
{ "resource": "" }
q42395
WSGIPlugin.set_server
train
def set_server(self, wsgi_app, fnc_serve=None): """ figures out how the wsgi application is to be served according to config """ self.set_wsgi_app(wsgi_app) ssl_config = self.get_config("ssl") ssl_context = {} if self.get_config("server") == "gevent": ...
python
{ "resource": "" }
q42396
SlugPreviewField.pre_save
train
def pre_save(self, instance, add): """ Auto-generate the slug if needed. """ # get currently entered slug value = self.value_from_object(instance) slug = None # auto populate (if the form didn't do that already). # If you want unique_with logic, use djang...
python
{ "resource": "" }
q42397
FirstSlotSlicer
train
def FirstSlotSlicer(primary_query, secondary_query, limit=30): # noqa """ Inject the first object from a queryset into the first position of a reading list. :param primary_queryset: djes.LazySearch object. Default queryset for reading list. :param secondary_queryset: djes.LazySearch object. first resu...
python
{ "resource": "" }
q42398
SearchSlicer.register_queryset
train
def register_queryset(self, queryset, validator=None, default=False): """ Add a given queryset to the iterator with custom logic for iteration. :param queryset: List of objects included in the reading list. :param validator: Custom logic to determine a queryset's position in a reading_l...
python
{ "resource": "" }
q42399
Command.get_month_start_date
train
def get_month_start_date(self): """Returns the first day of the current month""" now = timezone.now() return timezone.datetime(day=1, month=now.month, year=now.year, tzinfo=now.tzinfo)
python
{ "resource": "" }