_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q42900
reindex
train
def reindex(): '''Reindex all advices''' header('Reindexing all advices') echo('Deleting index {0}', white(es.index_name)) if es.indices.exists(es.index_name): es.indices.delete(index=es.index_name) es.initialize() idx = 0 for idx, advice in enumerate(Advice.objects, 1): ind...
python
{ "resource": "" }
q42901
static
train
def static(path, no_input): '''Compile and collect static files into path''' log = logging.getLogger('webassets') log.addHandler(logging.StreamHandler()) log.setLevel(logging.DEBUG) cmdenv = CommandLineEnvironment(assets, log) cmdenv.build() if exists(path): warning('{0} directory ...
python
{ "resource": "" }
q42902
anon
train
def anon(): '''Check for candidates to anonymization''' header(anon.__doc__) filename = 'urls_to_check.csv' candidates = Advice.objects(__raw__={ '$or': [ {'subject': { '$regex': '(Monsieur|Madame|Docteur|Mademoiselle)\s+[^X\s\.]{3}', '$options': 'imx...
python
{ "resource": "" }
q42903
Brain.login
train
def login(self, **kwargs): """Logs the current user into the server with the passed in credentials. If successful the apiToken will be changed to match the passed in credentials. :param apiToken: use the passed apiToken to authenticate :param user_id: optional instead of apiToken, must be passed with token...
python
{ "resource": "" }
q42904
Brain.createAssetFromURL
train
def createAssetFromURL(self, url, async=False, metadata=None, callback=None): """Users the passed URL to load data. If async=false a json with the result is returned otherwise a json with an asset_id is returned. :param url: :param metadata: arbitrary additional description information for the asset :p...
python
{ "resource": "" }
q42905
reload
train
def reload(filename=None, url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml", loader_class=None): u"""reload google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library.""" if loader_class is None: loader_clas...
python
{ "resource": "" }
q42906
AnsiVault.is_file_encrypted
train
def is_file_encrypted(self, filename): ''' Given a file. Check if it is already encrypted. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return False fhandle = open(filename, "rb") data = fhandle.read(...
python
{ "resource": "" }
q42907
common_start
train
def common_start(*args): """ returns the longest common substring from the beginning of sa and sb """ def _iter(): for s in zip(*args): if len(set(s)) < len(args): yield s[0] else: return out = "".join(_iter()).strip() result = [s for s in...
python
{ "resource": "" }
q42908
passgen
train
def passgen(length=12, punctuation=False, digits=True, letters=True, case="both", **kwargs): """Generate random password. Args: length (int): The length of the password. Must be greater than zero. Defaults to 12. punctuation (bool): Whether to use punctuation or not. D...
python
{ "resource": "" }
q42909
main
train
def main(): """The main entry point for command line invocation. It's output is adjusted by command line arguments. By default it outputs 10 passwords. For help on accepted arguments, run:: $ passgen -h Or:: $ python -m passgen -h """ parser = argparse.ArgumentParser( ...
python
{ "resource": "" }
q42910
BaseCommand.main
train
def main(cls): """Setuptools console-script entrypoint""" cmd = cls() cmd._parse_args() cmd._setup_logging() response = cmd._run() output = cmd._handle_response(response) if output is not None: print(output)
python
{ "resource": "" }
q42911
SetOrgMiddleware.set_language
train
def set_language(self, request, org): """Set the current language from the org configuration.""" if org: lang = org.language or settings.DEFAULT_LANGUAGE translation.activate(lang)
python
{ "resource": "" }
q42912
SetOrgMiddleware.set_timezone
train
def set_timezone(self, request, org): """Set the current timezone from the org configuration.""" if org and org.timezone: timezone.activate(org.timezone)
python
{ "resource": "" }
q42913
TrackContainer.add
train
def add(self, obj): """ Add pre-created tracks. If the tracks are already created, we hijack the data. This way the pointer to the pre-created tracks are still valid. """ obj.controller = self.controller # Is the track already loaded or created? track = se...
python
{ "resource": "" }
q42914
Track.row_value
train
def row_value(self, row): """Get the tracks value at row""" irow = int(row) i = self._get_key_index(irow) if i == -1: return 0.0 # Are we dealing with the last key? if i == len(self.keys) - 1: return self.keys[-1].value return TrackKey.in...
python
{ "resource": "" }
q42915
Track.add_or_update
train
def add_or_update(self, row, value, kind): """Add or update a track value""" i = bisect.bisect_left(self.keys, row) # Are we simply replacing a key? if i < len(self.keys) and self.keys[i].row == row: self.keys[i].update(value, kind) else: self.keys.insert...
python
{ "resource": "" }
q42916
Track.delete
train
def delete(self, row): """Delete a track value""" i = self._get_key_index(row) del self.keys[i]
python
{ "resource": "" }
q42917
Track._get_key_index
train
def _get_key_index(self, row): """Get the key that should be used as the first interpolation value""" # Don't bother with empty tracks if len(self.keys) == 0: return -1 # No track values are defined yet if row < self.keys[0].row: return -1 # Get ...
python
{ "resource": "" }
q42918
Track.load
train
def load(self, filepath): """Load the track file""" with open(filepath, 'rb') as fd: num_keys = struct.unpack(">i", fd.read(4))[0] for i in range(num_keys): row, value, kind = struct.unpack('>ifb', fd.read(9)) self.keys.append(TrackKey(row, value, ...
python
{ "resource": "" }
q42919
Track.save
train
def save(self, path): """Save the track""" name = Track.filename(self.name) with open(os.path.join(path, name), 'wb') as fd: fd.write(struct.pack('>I', len(self.keys))) for k in self.keys: fd.write(struct.pack('>ifb', k.row, k.value, k.kind))
python
{ "resource": "" }
q42920
iri2uri
train
def iri2uri(uri): """Convert an IRI to a URI. Note that IRIs must be passed in a unicode strings. That is, do not utf-8 encode the IRI before passing it into the function.""" assert uri != None, 'iri2uri must be passed a non-none string!' original = uri if isinstance(uri ,str): (scheme, authority, path, query...
python
{ "resource": "" }
q42921
AnsibleRunner.validate_host_parameters
train
def validate_host_parameters(self, host_list, remote_user): ''' Validate and set the host list and remote user parameters. ''' if host_list is None: host_list = self.host_list if remote_user is None: remote_user = self.remote_user if host_list is...
python
{ "resource": "" }
q42922
AnsibleRunner.validate_results
train
def validate_results(self, results, checks=None): ''' Valdiate results from the Anisble Run. ''' results['status'] = 'PASS' failed_hosts = [] ################################################### # First validation is to make sure connectivity to # all the ...
python
{ "resource": "" }
q42923
AnsibleRunner.ansible_perform_operation
train
def ansible_perform_operation(self, host_list=None, remote_user=None, remote_pass=None, module=None, complex_args=None, ...
python
{ "resource": "" }
q42924
PoToXls.strings
train
def strings(self): """ Write strings sheet. """ sheet = self.result.add_sheet("strings") self.header(sheet, "strings") n_row = 1 # row number for entry in self.po: row = sheet.row(n_row) row.write(0, entry.msgid) row.write(1...
python
{ "resource": "" }
q42925
PoToXls.metadata
train
def metadata(self): """ Write metadata sheet. """ sheet = self.result.add_sheet("metadata") self.header(sheet, "metadata") n_row = 1 # row number for k in self.po.metadata: row = sheet.row(n_row) row.write(0, k) row.write(1,...
python
{ "resource": "" }
q42926
PoToXls.convert
train
def convert(self, *args, **kwargs): """ Yes it is, thanks captain. """ self.strings() self.metadata() # save file self.result.save(self.output())
python
{ "resource": "" }
q42927
sync_from_remote
train
def sync_from_remote(org, syncer, remote): """ Sync local instance against a single remote object :param * org: the org :param * syncer: the local model syncer :param * remote: the remote object :return: the outcome (created, updated or deleted) """ identity = syncer.identify_remote(rem...
python
{ "resource": "" }
q42928
sync_local_to_set
train
def sync_local_to_set(org, syncer, remote_set): """ Syncs an org's set of local instances of a model to match the set of remote objects. Local objects not in the remote set are deleted. :param org: the org :param * syncer: the local model syncer :param remote_set: the set of remote objects ...
python
{ "resource": "" }
q42929
sync_local_to_changes
train
def sync_local_to_changes(org, syncer, fetches, deleted_fetches, progress_callback=None): """ Sync local instances against iterators which return fetches of changed and deleted remote objects. :param * org: the org :param * syncer: the local model syncer :param * fetches: an iterator returning fetc...
python
{ "resource": "" }
q42930
Rpn.fsto
train
def fsto(self): """sto operation. """ a = float(self.tmpopslist.pop()) var = self.opslist.pop() if isinstance(var, basestring): self.variables.update({var: a}) return a else: print("Can only sto into a variable.") return 'ER...
python
{ "resource": "" }
q42931
Rpn.solve
train
def solve(self): """Solve rpn expression, return None if not valid.""" popflag = True self.tmpopslist = [] while True: while self.opslist and popflag: op = self.opslist.pop() if self.is_variable(op): op = self.variables.get(...
python
{ "resource": "" }
q42932
build_sort
train
def build_sort(): '''Build sort query paramter from kwargs''' sorts = request.args.getlist('sort') sorts = [sorts] if isinstance(sorts, basestring) else sorts sorts = [s.split(' ') for s in sorts] return [{SORTS[s]: d} for s, d in sorts if s in SORTS]
python
{ "resource": "" }
q42933
show_list_translations
train
def show_list_translations(context, item): """ Return the widget to select the translations we want to order or delete from the item it's being edited :param context: :param item: :return: """ if not item: return manager = Manager() manager.set_master(item) ct_item...
python
{ "resource": "" }
q42934
Table._xml_pretty_print
train
def _xml_pretty_print(self, data): """Pretty print xml data """ raw_string = xtree.tostring(data, 'utf-8') parsed_string = minidom.parseString(raw_string) return parsed_string.toprettyxml(indent='\t')
python
{ "resource": "" }
q42935
Table._create_table_xml_file
train
def _create_table_xml_file(self, data, fname=None): """Creates a xml file of the table """ content = self._xml_pretty_print(data) if not fname: fname = self.name with open(fname+".xml", 'w') as f: f.write(content)
python
{ "resource": "" }
q42936
Table.save
train
def save(self, name=None, path=None): """Save file as xml """ if path : name = os.path.join(path,name) try: self._create_table_xml_file(self.etree, name) except (Exception,) as e: print(e) return False return True
python
{ "resource": "" }
q42937
Table.addBinder
train
def addBinder(self, binder): """Adds a binder to the file """ root = self.etree bindings = root.find('bindings') bindings.append(binder.etree) return True
python
{ "resource": "" }
q42938
Table.removeBinder
train
def removeBinder(self, name): """Remove a binder from a table """ root = self.etree t_bindings = root.find('bindings') t_binder = t_bindings.find(name) if t_binder : t_bindings.remove(t_binder) return True return...
python
{ "resource": "" }
q42939
CentrifugoAuthentication.post
train
def post(self, request, *args, **kwargs): """ Returns a token identifying the user in Centrifugo. """ current_timestamp = "%.0f" % time.time() user_id_str = u"{0}".format(request.user.id) token = generate_token(settings.CENTRIFUGE_SECRET, user_id_str, "{0}".format(curren...
python
{ "resource": "" }
q42940
Base.removeFunction
train
def removeFunction(self): """Remove function tag """ root = self.etree t_execute = root.find('execute') try: root.remove(t_execute) return True except (Exception,) as e: print(e) return False
python
{ "resource": "" }
q42941
BaseBinder._buildElementTree
train
def _buildElementTree(self,): """Turns object into a Element Tree """ t_binder = ctree.Element(self.name) for k,v in self.__dict__.items(): if k not in ('name', 'urls', 'inputs', 'paging') and v : t_binder.set(k,v) self.etree = t_binder retur...
python
{ "resource": "" }
q42942
BaseBinder.addUrl
train
def addUrl(self, url): """Add url to binder """ if url not in self.urls: self.urls.append(url) root = self.etree t_urls = root.find('urls') if not t_urls: t_urls = ctree.SubElement(root, 'urls') t_url = ctree.SubElement(t_urls, 'url') ...
python
{ "resource": "" }
q42943
BaseBinder.removeUrl
train
def removeUrl(self, url): """Remove passed url from a binder """ root = self.etree t_urls = root.find('urls') if not t_urls: return False for t_url in t_urls.findall('url'): if t_url.text == url.strip(): t_urls.remove(t_url) ...
python
{ "resource": "" }
q42944
BaseBinder.addPaging
train
def addPaging(self,paging): """Add paging to Binder """ if not vars(self).get('paging', None): self.paging = paging root = self.etree try: root.append(paging.etree) return True except (Exception,) as e: print(e) re...
python
{ "resource": "" }
q42945
BaseBinder.removePaging
train
def removePaging(self,): """Remove paging from Binder """ root = self.etree t_paging = root.find('paging') try: root.remove(t_paging) return True except (Exception,) as e: print(e) return False
python
{ "resource": "" }
q42946
BaseInput._buildElementTree
train
def _buildElementTree(self,): """Turn object into an ElementTree """ t_elt = ctree.Element(self.name) for k,v in [ (key,value) for key,value in self.__dict__.items() if key != 'name']: # Excluding name from list of items if v and v != 'false' : t_elt.set(k if...
python
{ "resource": "" }
q42947
BasePaging._buildElementTree
train
def _buildElementTree(self,): """Turn object into an Element Tree """ t_paging = ctree.Element('paging') t_paging.set('model', self.model) for key in self.__dict__.keys(): if key != 'model': t_tag = ctree.SubElement(t_paging, key) for ...
python
{ "resource": "" }
q42948
get_application_choices
train
def get_application_choices(): """ Get the select options for the application selector :return: """ result = [] keys = set() for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel) and ct.app_label not in keys...
python
{ "resource": "" }
q42949
get_model_choices
train
def get_model_choices(): """ Get the select options for the model selector :return: """ result = [] for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel): result.append( ('{} ...
python
{ "resource": "" }
q42950
has_field
train
def has_field(mc, field_name): """ detect if a model has a given field has :param field_name: :param mc: :return: """ try: mc._meta.get_field(field_name) except FieldDoesNotExist: return False return True
python
{ "resource": "" }
q42951
reader
train
def reader(f): '''CSV Reader factory for CADA format''' return unicodecsv.reader(f, encoding='utf-8', delimiter=b',', quotechar=b'"')
python
{ "resource": "" }
q42952
writer
train
def writer(f): '''CSV writer factory for CADA format''' return unicodecsv.writer(f, encoding='utf-8', delimiter=b',', quotechar=b'"')
python
{ "resource": "" }
q42953
from_row
train
def from_row(row): '''Create an advice from a CSV row''' subject = (row[5][0].upper() + row[5][1:]) if row[5] else row[5] return Advice.objects.create( id=row[0], administration=cleanup(row[1]), type=row[2], session=datetime.strptime(row[4], '%d/%m/%Y'), subject=clean...
python
{ "resource": "" }
q42954
to_row
train
def to_row(advice): '''Serialize an advice into a CSV row''' return [ advice.id, advice.administration, advice.type, advice.session.year, advice.session.strftime('%d/%m/%Y'), advice.subject, ', '.join(advice.topics), ', '.join(advice.tags), ...
python
{ "resource": "" }
q42955
clean_dict
train
def clean_dict(data): """Remove None-valued keys from a dictionary, recursively.""" if is_mapping(data): out = {} for k, v in data.items(): if v is not None: out[k] = clean_dict(v) return out elif is_sequence(data): return [clean_dict(d) for d in d...
python
{ "resource": "" }
q42956
keys_values
train
def keys_values(data, *keys): """Get an entry as a list from a dict. Provide a fallback key.""" values = [] if is_mapping(data): for key in keys: if key in data: values.extend(ensure_list(data[key])) return values
python
{ "resource": "" }
q42957
userinput
train
def userinput(prompttext="", times=1): """ Get the input of the user via a universally secure method. :type prompttext: string :param prompttext: The text to display while receiving the data. :type times: integer :param times: The amount of times to ask the user. If value is not 1, a list will...
python
{ "resource": "" }
q42958
shellinput
train
def shellinput(initialtext='>> ', splitpart=' '): """ Give the user a shell-like interface to enter commands which are returned as a multi-part list containing the command and each of the arguments. :type initialtext: string :param initialtext: Set the text to be displayed as the prompt. :...
python
{ "resource": "" }
q42959
splitstring
train
def splitstring(string, splitcharacter=' ', part=None): """ Split a string based on a character and get the parts as a list. :type string: string :param string: The string to split. :type splitcharacter: string :param splitcharacter: The character to split for the string. :type part: inte...
python
{ "resource": "" }
q42960
pykeyword
train
def pykeyword(operation='list', keywordtotest=None): """ Check if a keyword exists in the Python keyword dictionary. :type operation: string :param operation: Whether to list or check the keywords. Possible options are 'list' and 'in'. :type keywordtotest: string :param keywordtotest: The keyw...
python
{ "resource": "" }
q42961
warnconfig
train
def warnconfig(action='default'): """ Configure the Python warnings. :type action: string :param action: The configuration to set. Options are: 'default', 'error', 'ignore', 'always', 'module' and 'once'. """ # If action is 'default' if action.lower() == 'default': # Change warning...
python
{ "resource": "" }
q42962
happybirthday
train
def happybirthday(person): """ Sing Happy Birthday """ print('Happy Birthday To You') time.sleep(2) print('Happy Birthday To You') time.sleep(2) print('Happy Birthday Dear ' + str(person[0].upper()) + str(person[1:])) time.sleep(2) print('Happy Birthday To You')
python
{ "resource": "" }
q42963
convertbinary
train
def convertbinary(value, argument): """ Convert text to binary form or backwards. :type value: string :param value: The text or the binary text :type argument: string :param argument: The action to perform on the value. Can be "to" or "from". """ if argument == 'to': return bi...
python
{ "resource": "" }
q42964
reversetext
train
def reversetext(contenttoreverse, reconvert=True): """ Reverse any content :type contenttoreverse: string :param contenttoreverse: The content to be reversed :type reeval: boolean :param reeval: Wether or not to reconvert the object back into it's initial state. Default is "True". """ ...
python
{ "resource": "" }
q42965
convertascii
train
def convertascii(value, command='to'): """ Convert an ASCII value to a symbol :type value: string :param value: The text or the text in ascii form. :type argument: string :param argument: The action to perform on the value. Can be "to" or "from". """ command = command.lower() if co...
python
{ "resource": "" }
q42966
availchars
train
def availchars(charactertype): """ Get all the available characters for a specific type. :type charactertype: string :param charactertype: The characters to get. Can be 'letters', 'lowercase, 'uppercase', 'digits', 'hexdigits', 'punctuation', 'printable', 'whitespace' or 'all'. >>> availchars("low...
python
{ "resource": "" }
q42967
textbetween
train
def textbetween(variable, firstnum=None, secondnum=None, locationoftext='regular'): """ Get The Text Between Two Parts """ if locationoftext == 'regular': return variable[firstnum:secondnum] elif locationoftext == 'toend': return variab...
python
{ "resource": "" }
q42968
letternum
train
def letternum(letter): """ Get The Number Corresponding To A Letter """ if not isinstance(letter, str): raise TypeError("Invalid letter provided.") if not len(letter) == 1: raise ValueError("Invalid letter length provided.") letter = letter.lower() alphaletters = string.ascii...
python
{ "resource": "" }
q42969
wordvalue
train
def wordvalue(word): """ Get the value of each letter of a string's position in the alphabet added up :type word: string :param word: The word to find the value of """ # Set total to 0 total = 0 # For each character of word for i in enumerate(word): # Add it's letter value...
python
{ "resource": "" }
q42970
spacelist
train
def spacelist(listtospace, spacechar=" "): """ Convert a list to a string with all of the list's items spaced out. :type listtospace: list :param listtospace: The list to space out. :type spacechar: string :param spacechar: The characters to insert between each list item. Default is: " ". ...
python
{ "resource": "" }
q42971
numlistbetween
train
def numlistbetween(num1, num2, option='list', listoption='string'): """ List Or Count The Numbers Between Two Numbers """ if option == 'list': if listoption == 'string': output = '' output += str(num1) for currentnum in range(num1 + 1, num2 + 1): ...
python
{ "resource": "" }
q42972
textalign
train
def textalign(text, maxlength, align='left'): """ Align Text When Given Full Length """ if align == 'left': return text elif align == 'centre' or align == 'center': spaces = ' ' * (int((maxlength - len(text)) / 2)) elif align == 'right': spaces = (maxlength - len(text)) ...
python
{ "resource": "" }
q42973
shapesides
train
def shapesides(inputtocheck, inputtype='shape'): """ Get the sides of a shape. inputtocheck: The amount of sides or the shape to be checked, depending on the value of inputtype. inputtype: The type of input provided. Can be: 'shape', 'sides'. """ # Define the array of sides to...
python
{ "resource": "" }
q42974
autosolve
train
def autosolve(equation): """ Automatically solve an easy maths problem. :type equation: string :param equation: The equation to calculate. >>> autosolve("300 + 600") 900 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[0]) except Value...
python
{ "resource": "" }
q42975
autohard
train
def autohard(equation): """ Automatically solve a hard maths problem. :type equation: string :param equation: The equation to solve. >>> autohard("log 10") 2.302585092994046 """ try: # Try to set a variable to an integer num1 = int(equation.split(" ")[1]) except V...
python
{ "resource": "" }
q42976
equation
train
def equation(operation, firstnum, secondnum): """ Solve a simple maths equation manually """ if operation == 'plus': return firstnum + secondnum elif operation == 'minus': return firstnum - secondnum elif operation == 'multiply': return firstnum * secondnum elif opera...
python
{ "resource": "" }
q42977
scientific
train
def scientific(number, operation, number2=None, logbase=10): """ Solve scientific operations manually """ if operation == 'log': return math.log(number, logbase) elif operation == 'acos': return math.acos(number) elif operation == 'asin': return math.asin(number) elif...
python
{ "resource": "" }
q42978
fracsimplify
train
def fracsimplify(numerator, denominator): """ Simplify a fraction. :type numerator: integer :param numerator: The numerator of the fraction to simplify :type denominator: integer :param denominator: The denominator of the fraction to simplify :return: The simplified fraction :rtype: l...
python
{ "resource": "" }
q42979
circleconvert
train
def circleconvert(amount, currentformat, newformat): """ Convert a circle measurement. :type amount: number :param amount: The number to convert. :type currentformat: string :param currentformat: The format of the provided value. :type newformat: string :param newformat: The intended ...
python
{ "resource": "" }
q42980
amountdiv
train
def amountdiv(number, minnum, maxnum): """ Get the amount of numbers divisable by a number. :type number: number :param number: The number to use. :type minnum: integer :param minnum: The minimum number to check. :type maxnum: integer :param maxnum: The maximum number to check. >...
python
{ "resource": "" }
q42981
constant
train
def constant(constanttype): """ Get A Constant """ constanttype = constanttype.lower() if constanttype == 'pi': return math.pi elif constanttype == 'e': return math.e elif constanttype == 'tau': return math.tau elif constanttype == 'inf': return math.inf ...
python
{ "resource": "" }
q42982
average
train
def average(numbers, averagetype='mean'): """ Find the average of a list of numbers :type numbers: list :param numbers: The list of numbers to find the average of. :type averagetype: string :param averagetype: The type of average to find. >>> average([1, 2, 3, 4, 5], 'median') 3 "...
python
{ "resource": "" }
q42983
numprop
train
def numprop(value, propertyexpected): """ Check If A Number Is A Type """ if propertyexpected == 'triangular': x = (math.sqrt(8 * value + 1) - 1) / 2 return bool(x - int(x) > 0) elif propertyexpected == 'square': return math.sqrt(value).is_integer() elif propertyexpected ...
python
{ "resource": "" }
q42984
compare
train
def compare(value1, value2, comparison): """ Compare 2 values :type value1: object :param value1: The first value to compare. :type value2: object :param value2: The second value to compare. :type comparison: string :param comparison: The comparison to make. Can be "is", "or", "and". ...
python
{ "resource": "" }
q42985
factors
train
def factors(number): """ Find all of the factors of a number and return it as a list. :type number: integer :param number: The number to find the factors for. """ if not (isinstance(number, int)): raise TypeError( "Incorrect number type provided. Only integers are accepted....
python
{ "resource": "" }
q42986
randomnum
train
def randomnum(minimum=1, maximum=2, seed=None): """ Generate a random number. :type minimum: integer :param minimum: The minimum number to generate. :type maximum: integer :param maximum: The maximum number to generate. :type seed: integer :param seed: A seed to use when generating th...
python
{ "resource": "" }
q42987
tokhex
train
def tokhex(length=10, urlsafe=False): """ Return a random string in hexadecimal """ if urlsafe is True: return secrets.token_urlsafe(length) return secrets.token_hex(length)
python
{ "resource": "" }
q42988
isfib
train
def isfib(number): """ Check if a number is in the Fibonacci sequence. :type number: integer :param number: Number to check """ num1 = 1 num2 = 1 while True: if num2 < number: tempnum = num2 num2 += num1 num1 = tempnum elif num2 == nu...
python
{ "resource": "" }
q42989
isprime
train
def isprime(number): """ Check if a number is a prime number :type number: integer :param number: The number to check """ if number == 1: return False for i in range(2, int(number**0.5) + 1): if number % i == 0: return False return True
python
{ "resource": "" }
q42990
convertbase
train
def convertbase(number, base=10): """ Convert a number in base 10 to another base :type number: number :param number: The number to convert :type base: integer :param base: The base to convert to. """ integer = number if not integer: return '0' sign = 1 if integer > 0 ...
python
{ "resource": "" }
q42991
quadrant
train
def quadrant(xcoord, ycoord): """ Find the quadrant a pair of coordinates are located in :type xcoord: integer :param xcoord: The x coordinate to find the quadrant for :type ycoord: integer :param ycoord: The y coordinate to find the quadrant for """ xneg = bool(xcoord < 0) yneg =...
python
{ "resource": "" }
q42992
flipcoords
train
def flipcoords(xcoord, ycoord, axis): """ Flip the coordinates over a specific axis, to a different quadrant :type xcoord: integer :param xcoord: The x coordinate to flip :type ycoord: integer :param ycoord: The y coordinate to flip :type axis: string :param axis: The axis to flip acr...
python
{ "resource": "" }
q42993
lcm
train
def lcm(num1, num2): """ Find the lowest common multiple of 2 numbers :type num1: number :param num1: The first number to find the lcm for :type num2: number :param num2: The second number to find the lcm for """ if num1 > num2: bigger = num1 else: bigger = num2 ...
python
{ "resource": "" }
q42994
hcf
train
def hcf(num1, num2): """ Find the highest common factor of 2 numbers :type num1: number :param num1: The first number to find the hcf for :type num2: number :param num2: The second number to find the hcf for """ if num1 > num2: smaller = num2 else: smaller = num1 ...
python
{ "resource": "" }
q42995
randstring
train
def randstring(length=1): """ Generate a random string consisting of letters, digits and punctuation :type length: integer :param length: The length of the generated string. """ charstouse = string.ascii_letters + string.digits + string.punctuation newpass = '' for _ in range(length): ...
python
{ "resource": "" }
q42996
case
train
def case(text, casingformat='sentence'): """ Change the casing of some text. :type text: string :param text: The text to change the casing of. :type casingformat: string :param casingformat: The format of casing to apply to the text. Can be 'uppercase', 'lowercase', 'sentence' or 'caterpillar'...
python
{ "resource": "" }
q42997
encryptstring
train
def encryptstring(text, password): """ Encrypt a string according to a specific password. :type text: string :param text: The text to encrypt. :type pass: string :param pass: The password to encrypt the text with. """ enc = [] for i in enumerate(text): key_c = password[i[0...
python
{ "resource": "" }
q42998
decryptstring
train
def decryptstring(enc, password): """ Decrypt an encrypted string according to a specific password. :type enc: string :param enc: The encrypted text. :type pass: string :param pass: The password used to encrypt the text. """ dec = [] enc = base64.urlsafe_b64decode(enc).decode() ...
python
{ "resource": "" }
q42999
pipinstall
train
def pipinstall(packages): """ Install one or more pip packages. :type packages: string or list :param packages: The package or list of packages to install. :raises TypeError: Nor a string or a list was provided. """ if isinstance(packages, str): if hasattr(pip, 'main'): ...
python
{ "resource": "" }